Use ajax to clear JavaScript, CSS, and images cached by the browser

Source: Internet
Author: User
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
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.