Help with aggressive JavaScript caching

2019-01-31 22:00发布

I've run into a problem where I make changes to a few JavaScript files that are referenced in an HTML file, but the browser doesn't see the changes. It holds onto the copy cached in the browser, even though the web server has a newer version.

Not until I force the browser to clear the cache do I see the changes.

Is this a web-server configuration? Do I need to set my JavaScript files to never cache? I've seen some interesting techniques in the Google Web Toolkit where they actually create a new JavaScript file name any time an update is made. I believe this is to prevent proxies and browsers from keeping old versions of the JavaScript files with the same names.

Is there a list of best practices somewhere?

10条回答
SAY GOODBYE
2楼-- · 2019-01-31 22:13

I am also of the method of just renaming things. It never fails, and is fairly easy to do.

查看更多
家丑人穷心不美
3楼-- · 2019-01-31 22:21

@Jason and Darren

IE6 treats anything with a query string as uncacheable. You should find another way to get the version number into the url, such as a fake directory:

<script src="/js/version/MyScript.js"/>

and just remove that first directory level after js on the server side before fulfilling the request.

EDIT: Sorry all; it is Squid, not IE6, that won't cache with a query string. More info here.

查看更多
来,给爷笑一个
4楼-- · 2019-01-31 22:23

With every release, we simply prepend a monotonically increasing integer to the root path of all our static assets, which forces the client to reload (we've seen the query string method break in IE6 before). For example:

  • Release 1: http://www.foo.com/1/js/foo.js
  • Release 2: http://www.foo.com/2/js/foo.js

It requires rejiggering links with each release, but we've built functionality to automatically change the links into our deployment tools.

Once you do this, you can use Expires/Cache-Control headers that let the client cache JS resources "forever", since the path changes with each release, which i think is what @JasonCohen was getting at.

查看更多
爷、活的狠高调
5楼-- · 2019-01-31 22:27

Some very useful techniques in here even if you are not planning to use powershell to automate deployment.

查看更多
Ridiculous、
6楼-- · 2019-01-31 22:28

is your webserver sending the right headers to tell the browser it has a new version? I've also added the date to the querystring before. ie myscripts.js?date=4/14/2008 12:45:03 (only the date would be encoded)

查看更多
Lonely孤独者°
7楼-- · 2019-01-31 22:34

For what it is worth, I saw deviantART site, quite a big one, serving their JS files as 54504.js. I just checked and see they now serve them as v6core.css?-5855446573 v6core_jc.js?4150339741 etc.

If the problem of query string comes from the server, I suppose you can control that more or less.

查看更多
登录 后发表回答