Skip to content Skip to sidebar Skip to footer

How Can I Request That Browsers Always Update (a.k.a. Never Cache) Certain Page Elements, Such As Css Sheets?

I've noticed an issue while developing my pages that's always bothered me: while Firefox (my general 'dev' browser) always updates CSS and images when they change on the server, In

Solution 1:

It's a good practice to design your site so that the client only needs to fetch external JavaScript and CSS once.

Set up external resources to expire 1 year in the future. Append a version number to each file name, so instead of "style.css", use "style-1.2.4.css" and then when you want to update the client's CSS, increment the version number.

Incrementing the version number forces the client to download the updated file because it is seen as a totally separate resource.

Solution 2:

Add a little random query string at the end of all URLs. It's ugly but it works when developing. For example:

<linkrel="stylesheet"type="text/css"href="/mycss.css?foo=<?phpecho rand(); ?>"/>

You can do the same for scripts, background images, etc. (And don't forget to remove these things when your site goes live ;))

Solution 3:

This is only an issue during development, when the files are changing frequently. Once you've published the site, visitors will get the current version, and the caching mechanisms will do more or less what you want.

Rather than modify how my sites work, I have simply developed the habit of clearing my cache before refreshes during development. In Firefox, as you said, this is not usually an issue, but if I need to be really sure, I use Shift+Ctrl+Del, Enter (and my Clear Private Data settings leave only "Cache" checked.) And on IE, there's the old Shift+F5.

Of course, as others have mentioned, a random query string on your volatile files can save you a few keystrokes. But understand that this is in fact just for your own convenience and not really necessary for the production site.

Solution 4:

It's better if you put the last-change timestamp as GET-data at the end of the source - in this way you'll be sure that there wont be any cache errors.

It's just dumb to remove the cache completely since it will result in slower pages.

Solution 5:

If you're using apache, in your .htaccess for that css file:

<FilesMatch "mycssfile\.css$">
  Header set Cache-Control: "private, pre-check=0, post-check=0, max-age=0"
  Header set Expires: 0
  Header set Pragma: no-cache
</FilesMatch>

Post a Comment for "How Can I Request That Browsers Always Update (a.k.a. Never Cache) Certain Page Elements, Such As Css Sheets?"