Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Caching of CSS Files

I am developing a simple website using PHP.

Development Configuration : WAMP

Production Configuration : LAMP

While testing, I changed my CSS file, but when I reload the page my browser(not sure) still uses the old cached css.

I did some googling and found different solutions that I have already tried

  • Appending a query at the end of css css/main.css?78923
  • Using Ctrl + R (in Firefox) to force fetching of the resource
  • Disabling Firefox caching as well as using the Clear Cache Firefox add-on.

When none of this worked, I did some more googling, where I came across a stack page (here) where someone suggested that Apache caches the resources. So, the problem is not with the Firefox, but the server. The guy also suggested a solution that I did not understand (me being a newbie)

My question has two parts:

  1. Is it true that Apache caches resources? (How do I check if mine does?)
  2. How to prevent it from caching?

PS: copying and pasting the solution in stack question (the one that I have above as a link) did not work :(

like image 746
Ankit Avatar asked Mar 05 '12 00:03

Ankit


People also ask

Do CSS files get cached?

Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same.

What is CSS caching?

When a browser caches a CSS stylesheet, what it's doing is getting that stylesheet from the server once, saving it, and then serving its own saved version of that stylesheet to the user anytime the page being loaded requests it.

How long is CSS cached?

How does Caching Work? When the browser parses this HTML, it identifies that a CSS resource needs to load from https://www.example.com/app.css. The browser issues a request to the server for this file, the server returns the file and also tells the browser to cache it for 30 days.

How do I stop caching?

Here's how... When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache.


2 Answers

I've ran across this problem a few times and usually over come the problem on production sites by calling my css like this

<link rel="stylesheet" type="text/css" href="style.css?v=1" />

When you roll out an update just change the v=1 to v=2 and it will force all of your users browsers to grab the new style sheets. This will work for script files as well. If you view source on Google you will notice they use this approach as well.

like image 95
Mike L. Avatar answered Sep 29 '22 13:09

Mike L.


I used to have the same problem with my LAMP dev system, caused by a network mount. I managed to get rid of it by adding these two lines to my apache conf.

EnableMMAP off
EnableSendfile off
like image 39
Corubba Avatar answered Sep 29 '22 12:09

Corubba