Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, Internet Explorer does not always do this. Usually, I need to refresh the page in IE before it will ask the server for updated versions of things.

As I understand it, isn't the browser supposed to at least check the timestamps on all server side objects for each request, and then update them client side as necessary? Is there a way I can... not force, but.. "encourage" the browser to do this for certain items?

The main issue I'm having here is that I have some JavaScript on my pages that relies on the CSS being initialized a certain way, and vice versa. When one updates and the other does not (very common in IE when both are in their own external pages) it causes confusion, and occasional splatter results on the page. I can handle doing the "refresh the page" dance on my own for deving, but I don't want to have to encourage my users to "refresh the page or else" when I'm going on a scripting spree on the site.

Any advice would be greatly appreciated. The page itself updates without a hitch (it's PHP), so worst case scenario I could just spit the CSS and JavaScript out into the page itself, but that's really really ugly and of course I'm trying to avoid it at all costs.

like image 289
Nicholas Flynt Avatar asked Dec 01 '22 07:12

Nicholas Flynt


2 Answers

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.

like image 123
Dan Herbert Avatar answered Dec 03 '22 21:12

Dan Herbert


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

<link rel="stylesheet" type="text/css" href="/mycss.css?foo=<?php echo rand(); ?>"/>

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

like image 28
Etienne Perot Avatar answered Dec 03 '22 20:12

Etienne Perot