Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Invalidate Web Browser Cache Content

I've been really digging into Google Page Speed, optimizing a lot of the sites I'm working on to score well on that -- and quite successfully I'm proud to say.

The only downside I've come across is that by some of the caching stuff being done, small changes to JS and CSS tend not to cause a new copy of the files to download.

Is there any way when changes are made to the JS, CSS (or other resources) to force a new copy to download?

like image 544
Keefer Avatar asked Feb 03 '12 15:02

Keefer


People also ask

What is invalidating cache?

Cache invalidation refers to process during which web cache proxies declare cached content as invalid, meaning it will not longer be served as the most current piece of content when it is requested. Several invalidation methods are possible, including purging, refreshing and banning.

How do I invalidate CSS cache?

To invalidate cache is to remove the cache entries. There is no actual way to truly programatically do this for a browser. What we are actually talking about here is asking the web-server for a new file due the name of the file changing, not forceably removing the original file.


2 Answers

I'm running into similar issues sometimes that JS and CSS is cached to long. The solution that works for me is, adding an versionnumber or timestamp of the last update to the filename as querystring. This way the browser sees the file as changed and it will download it again.

Could be something like this for getting JS:

http://yourdomain.com/content/js/functions.js?v=201232
like image 87
Rob Avatar answered Oct 24 '22 15:10

Rob


I know that this is probably apparent, as, you could gather that the "versioning" technique for invalidating cache works for any static resource requested, but in case it is not, I will pipe in here.

We allow branding for some of our applications, and, that means image files very often change during the course of clients' lifetimes with us, as well as other static files previously mentioned. If the same name were to be used for a file, caching would present a problem. Handily, the idea of versioning the source of an image works just as well.

<img src="images/title.gif?v=2" />

Also, it is probably not important to mention this, but, the term "invalidating cache" in this regard, is not technically correct. To invalidate cache is to remove the cache entries. There is no actual way to truly programatically do this for a browser. What we are actually talking about here is asking the web-server for a new file due the name of the file changing, not forceably removing the original file. You can easily test this by changing a file version back and forth between an unused version, and an older used version, and seeing the HTTP 200 and 304 responses respectively.

enter image description here

like image 38
AlienFromCA Avatar answered Oct 24 '22 15:10

AlienFromCA