問題描述
如果可以判斷(在 javascript 執行中)GET XMLHTTPRequest 是否命中瀏覽器緩存而不是從服務器獲取響應?
If it possible to tell (within javascript execution) if a GET XMLHTTPRequest hit the browser cache instead of getting its response from the server?
推薦答案
來自 XMLHttpRequest 規范:
對于用戶代理導致的 304 Not Modified 響應生成的條件請求用戶代理必須像服務器一樣操作用適當的內容給出了 200 OK 響應.
For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content.
換句話說,瀏覽器將始終給出狀態碼 200 OK,即使對于命中瀏覽器緩存的請求也是如此.
In other words, the browser will always give status code 200 OK, even for requests that hit the browser cache.
但是,規范中還說:
用戶代理必須允許作者請求標頭覆蓋自動緩存驗證(例如 If-None-Match 或 If-Modified-Since),在這種情況下必須通過 304 Not Modified 響應.
The user agent must allow author request headers to override automatic cache validation (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through.
因此,有一種解決方法可以使 304 Not Modified 響應對您的 JavaScript 代碼可見.
So, there is a workaround to make the 304 Not Modified responses visible to your JavaScript code.
這篇關于如何判斷 XMLHTTPRequest 是否命中瀏覽器緩存的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!