在現代Web應用程序中,前端代碼充斥著大量的Ajax請求,如果對于Ajax請求可以使用瀏覽器緩存,那么可以顯著地減少網絡請求,提高程序響應速度。
1. Ajax Request
使用jQuery框架可以很方便的進行Ajax請求,示例代碼如下:
$.ajax({ url : 'url', dataType : "xml", cache: true, success : function(xml, status){ }});
非常簡單,注意其中的第4行代碼:cache:true,顯式的要求如果當前請求有緩存的話,直接使用緩存。如果該屬性設置為 false,則每次都會向服務器請求,Jquery的Comments如下:
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
前端的工作也就這么多了,這樣的話Ajax請求就可以利用瀏覽器緩存了嗎?
繼續看。
2. Http 協議
Http協議的header部分定義了關于客戶端是否應該做Cache,以及如何做Cache。具體參見Http Header Field Definitions 的 14.9 Cache-Control 和 14.21 Expires。這里簡單說一下:
Cache-Control
Cache-control用于控制HTTP緩存(在HTTP/1.0中可能部分沒實現,僅僅實現了Pragma: no-cache)
數據包中的格式:
Cache-Control: cache-directive
cache-directive可以為以下:
request時用到:
| "no-cache"
| "no-store"
| "max-age" "=" delta-seconds
| "max-stale" [ "=" delta-seconds ]
| "min-fresh" "=" delta-seconds
| "no-transform"
| "only-if-cached"
| "cache-extension"
response時用到:
| "public"
| "private" [ "=" <"> field-name <"> ]
| "no-cache" [ "=" <"> field-name <"> ]
| "no-store"
| "no-transform"
| "must-revalidate"
| "proxy-revalidate"
| "max-age" "=" delta-seconds
| "s-maxage" "=" delta-seconds
| "cache-extension"
說明:
-Public 指示響應可被任何緩存區緩存。
-Private 指示對于單個用戶的整個或部分響應消息,不能被共享緩存處理。這允許服務器僅僅描述當用戶的部分響應消息,此響應消息對于其他用戶的請求無效。
-no-cache 指示請求或響應消息不能緩存(HTTP/1.0用Pragma的no-cache替換)
-no-store 用于防止重要的信息被無意的發布。在請求消息中發送將使得請求和響應消息都不使用緩存。
-max-age 指示客戶端可以接收生存期不大于指定時間(以秒為單位)的響應。
-min-fresh 指示客戶端可以接收響應時間小于當前時間加上指定時間的響應。
-max-stale 指示客戶端可以接收超出超時期間的響應消息。如果指定max-stale消息的值,那么客戶端可以
接收超出超時期指定值之內的響應消息。
新聞熱點
疑難解答
圖片精選