简体   繁体   中英

Versioning Javascript Files to Prevent Unnecessary Cache Clearing

I version all of my client side JS files like "/js/myfile.js?v=3903948" so that my clients don't need to clear their browser cache to ensure they get the updated files. But every time I push an update, without fail, at least one person runs into a problem where they are running the old version and get some kind of error. I used to think that this was just them having already been on the page during the release and just needing to reload the browser, but this happened to me today when I was definitely not previously on the page. I browsed to the live site and was running the old code. I needed to do a browser refresh on that page to get the new file.

What can cause this?

PS I was using Chrome on Win7, but I have seen clients report this before on all different browsers.

If your main web page can also be cached, then the old version of that page can be requesting the old version of the JS file. JS file versioning works best if the page that actually refers to the JS file cannot be cached or has very short caching time.

I agree with jfriend00 about the webpage itself being cashed and thus requesting the old javascript version.

To prevent this, you can have the javascript file loaded by an ajax (Post) request, either requesting the server what is the accurate(latest) version number to download, or requesting the javascript itself and inserting it, eg in the head of the page.

Edit: see for example here

我向服务器提出了AJAX的快速请求,要求其提供期望的版本,然后如果客户端的脚本较旧,则强制他们刷新页面。

Seems that proxy or some load balancer is serving old content instead of new. Also check IIS/webserver settings how are these files cached/expired.

You can check what is going on on the wire with tools like Fiddler .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM