Tuesday, November 20, 2012

Style Sheets and Scripts Not Reloading

One of the problems I often encountered before in front-end side development for the web was style sheet and script caching.  It's not really a problem, as it is convenient and actually makes a lot of sense since these things shouldn't be reloaded every time.  But during development, there were a number of times I forgot about this and just pulled my hair in frustration, wondering why my changes do not reflect whenever I refresh the page, why my style sheets and scripts are not reloaded even if I do "shift-reload".

And of course it's because of caching.  So one of my colleagues taught me this:

<link rel="stylesheet"
href="/path/to/style.css?x=<?php echo time() ?>"
type="text/css">

This is in php, but you can do something similar with your choice of language.  Here, since time() gets the current timestamp and is thus ever changing, this way your styles and scripts will always be reloaded every time you refresh your page because of a different href from the one that has already been cached.

Note!  Only do this during development, so your style sheets and scripts will be cached when live.


:D