Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to append querystrings to images in an img tag and images in css to refresh cached items?

I know that a common practice is to set an expire time far in the future for css, javascript and image files and then make sure that all browsers fetches the latest content as soon the files changes by appending a querystring (or changing filename) like this

From this <link rel="stylesheet" type="text/css" href="base.css">:

to this:

<link rel="stylesheet" type="text/css" href="base.css?v=1234">

or:

<link rel="stylesheet" type="text/css" href="base_1234.css">

But what about images referenced in a css file?

// Inside base.css 
background: url(/img/logo.png)

// Is this necessary(?):
background: url(/img/logo.png?v=1234)

Or will /img/logo.png be reloaded when base.css changes filename to base.css?v=1234 or base_1234.css automatically?

And also, what about images in src for img-tags?

like image 880
Fredrik Avatar asked Jul 02 '12 20:07

Fredrik


2 Answers

The browser is making these requests after determining an absolute path, so if you are 'cache busting' your static assets in this way, you do need to do it for each file individually, no matter where it's called. You can, however, make it easer on yourself by making it a variable on the backend.

You can append the string as a variable that you only have to update in one place on your backend, probably in conjunction with a CSS pre-processor like LESS or SASS to get all your images.

Or use relative paths to your advantage by adding the version to the base url (site.com/folder/styles.css => site.com/v123/folder/styles.css). This can be added to an existing static asset base url variable in your app, then on the server you can just use a UrlRewrite to strip out the version. This way all the images relatively referred to from your CSS automatically get the version too, having the same 'cache busting' effect.

You could be extra clever and set the variable automatically as part of your build process as the last commit hash from you version control system - which will also make future debugging easier.

like image 171
swider Avatar answered Sep 20 '22 09:09

swider


From my experience the cache busting of the css is not recursive. So the querystring at the end of the image referenced in css is required to bust the cache.

To be sure all images are fresh you may want to also cache bust with the querystring version (img.png?v=1234).

like image 26
adamclerk Avatar answered Sep 22 '22 09:09

adamclerk