8
votes

When I make a page, link it to a CSS file, and open it in a browser, it works fine. But if a make a change and refresh the page again between very short time periods, the change is not reflected. But after sometime, when i refresh the page again, the changes appear.

So, somehow the browser keeps the CSS file cached and expires it after sometime. How to make the browser cache no CSS or HTML file. It would be better if i can block it on a particular domain.

I'm on Ubuntu, using Chrome and Firefox, trying to prevent browsers from caching CSS files on 'localhost'... How to do it...

Thanks...

4

4 Answers

6
votes

Something as simple as this should work:

<link rel="stylesheet" src="/css/screen.css?v={CURRENT_TIMESTAMP}">

Just replace {CURRENT_TIMESTAMP} with the actual timestamp in your server side code. This makes the browser think it's a new file because of the query string and it will be downloaded again. You could also use the actual modification time of the file (filemtime('/path/to/css/screen.css') if you're using PHP) which should prevent unnecessary downloads.

4
votes

You can open Developer Tools by pressing Ctrl+Shift+J and then you'll find a cog icon in bottom right. When you click on it you should see an option to disable caching.

1
votes

It would help to know how the website is hosted, as you can configure this in most web servers.

Also, it's a good idea to introduce a cache busting mechanism which would modify the links to the CSS files in question when you change the CSS files' contents. Browsers would then reload the CSS file because the HTML refers to a different URL.

A good example of a cache busting mechanism is the ruby on rails 3.1 asset pipeline which also minifies files and gzips them if the browser supports them:

Rails 3 - Asset Pipeline -- What does it mean to me?

http://2beards.net/2011/11/the-rails-3-asset-pipeline-in-about-5-minutes/

0
votes

The seemingly-inelegant but rock solid approach is to give the asset a new name, when the content changes. This solves the problem for all your users, not just you:

<link rel="stylesheet" src="/css/screen_034.css">
<link rel="stylesheet" src="/css/screen_035.css">
<link rel="stylesheet" src="/css/screen_036.css">

Or maybe (but it's more of a pain to change in an IDE, and sometimes causes unrelated problems with caching):

<link rel="stylesheet" src="/css/screen.css?pretend_version_number=034">

Nothing else works quite as well in large scale production environments, where millions of copies of an older css file may be sitting in various intermediate or browser caches. Some clients ignore cache control headers, and you don't really want caching subverted anyway, at least not in production.

In development you can press Ctrl+Shift+J (Chrome) and turn off caching.