天天看點

浏覽器緩存預設情況研究

緩存原理

使用者第一次請求頁面,伺服器沒有設定expired和max-age,設定了etag和last-modified,

使用者第二次請求頁面(正常請求,非強制重新整理),浏覽器會傳回304

使用者後續繼續請求頁面,浏覽器傳回幾次304之後,浏覽器會使用一個嘗試性的時間來使用本地的緩存,而不是直接去請求伺服器。

RFC位址:

Since origin servers do not always provide explicit expiration times, a cache MAY assign a heuristic expiration time when an explicit time is not specified, employing algorithms that use other header field values (such as the Last-Modified time)… If the response has a Last-Modified header field (Section 2.2 of [RFC7232]), caches are encouraged to use a heuristic expiration value that is no more than some fraction of the interval since that time. A typical setting of this fraction might be 10%. [https://tools.ietf.org/html/rfc7234#section-4.2.2]

源碼位址:https://cs.chromium.org/chromium/src/net/http/http_response_headers.cc?q=lifetimes.freshness&dr=C

截圖:

浏覽器緩存預設情況研究

測試情況

通路http://172.21.34.30:11000/app/call_example/頁面,jquery正常傳回

浏覽器緩存預設情況研究

在位址欄回車,重新加載頁面

浏覽器緩存預設情況研究

其中Last-Modified是 Tue, 04 Sep 2018 01:16:08 GMT

按照上面的邏輯,過期時間是now + (now-lastmodified)/10, 也就是Tue Sep 04 2018 09:47:40 GMT+0800

我将本地時間修改為Tue Sep 04 2018 10:47:40 GMT+0800

然後位址欄回車,重新加載頁面

浏覽器緩存預設情況研究

浏覽器傳回的是304,符合預期

但是問題是,經過一段時間,這些緩存在浏覽器中的資源被清除了,再次通路需要重新去下載下傳。

那麼浏覽器緩存的這些304的資源,什麼時候會被浏覽器清除?這取決于浏覽器的情況(例如浏覽器的存儲情況)和使用者設定。

繼續閱讀