Use ajax to clear JavaScript, CSS, and images cached by the browser
To reduce the network transmission pressure between the browser and the server, cache is usually performed on static files, such as JS, CSS, and modified images, that is, add the expires and cache-control parameters to the HTTP Response Headers of these files, and specify the cache time, in this way, the browser will not send any HTTP Request (except force refresh) to the server within a certain period of time, even if the server's JS, CSS, or image files have been updated multiple times during this period, however, the browser data is still the old data that can be cached at the beginning. Is there a way for the browser to obtain the latest data that has been modified?
Yes, the method is to use ajax to request the latest file on the server, and add the request header if-modified-since and cache-control, as follows:
$. Ajax ({
Type: "Get ",
URL: "static/cache. js ",
Datatype: "text ",
Beforesend: function (XMLHTTP ){
XMLHTTP. setRequestHeader ("If-modified-since", "0 ");
XMLHTTP. setRequestHeader ("cache-control", "No-Cache ");
}
});
Jquery is used here.
In this way, the browser will replace the latest file with the old local file.
Of course, another problem here is that JS must know that the server has updated the JS, CSS, and image, which can be solved by using cookies and time versions.
Jquery has ifmodified and cache parameters SINCE 1.2. You do not need to add the header yourself.
Ifmodified Boolean default: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the last-modified header. default value is false, ignoring the header.
Cache Boolean default: True
Added in jquery 1.2, if set to false it will force the pages that you request to not be cached by the browser.
$. Ajax ({
Type: "Get ",
URL: "static/cache. js ",
Datatype: "text ",
Cache: false,
Ifmodified: True
});