开发者

How to make sure a cached JavaScript and CSS files get reloaded?

开发者 https://www.devze.com 2022-12-18 21:26 出处:网络
Could anyone explain how to make sure that if I update my webapp, the user gets the latest version of files?

Could anyone explain how to make sure that if I update my webapp, the user gets the latest version of files?

Should I add a dynamic string ?version=random at the end of script and css files and change it as I开发者_如何转开发 roll out updates? Or what is a general strategy here?

Thank you, Boda Cydo.


Yes, the way you mention is very common and is a solid approach.

I personally use the Subversion revision number of my files, but you could use anything meaningful to you, even the last updated timestamp of the file.

StackOverflow uses the SVN revision number:

<script type="text/javascript" src="http://sstatic.net/so/js/master.js?v=6180">
</script> 


It turns out squid does not cache files with a GET parameter. You would have to use something like script.2010-02-14.js if you want squid to cache the file.

"But which is better: mylogo.1.2.gif or mylogo.gif?v=1.2? To gain the benefit of caching by popular proxies, avoid revving with a querystring and instead rev the filename itself."

http://webcache.googleusercontent.com/search?q=cache:JhDnwSNN-BEJ:www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/+http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/&cd=1&hl=en&ct=clnk&gl=us&client=opera&source=www.google.com


I usually put ?mtime at the end of the name for images, CSS files and Javascript files where mtime is the last modified time of the file.

You can alternatively use a version number that is incremented whenever the file is changed. This works well for libraries like jQuery that have official releases but tends to be more tedious than required for your own site's files that are simply changed as needed. Of course you can still use version numbers in this case but I tend to find it's unnecessarily tedious (being something else you need to maintain).


As you mention yourself, adding a query string to the stylesheet/script URL is a neat trick to gain control over when cached versions are "invalidated".

Rather than adding a random string, I usually use the last modification date of the relevant file from the file system. To improve the coolness factor, you can convert the date to a numeric form and format it in hex when building the URL :-)

<script type="text/javascript" src="script.js?v=1750493C88"></script>
<link rel="stylesheet" type="text/css" href="style.css?v=1750493C88" />
0

精彩评论

暂无评论...
验证码 换一张
取 消