I’ve found that browsers have a habit of keeping CSS files in the cache which is a problem when developing sites.
This is also an issue for anyone viewing your site as any changes made to the CSS will not be shown in the viewer’s browser.
I have found a way to allow changes to CSS files to instantly update in the browser when a page is loaded or refreshed without the need to clear the cache.
This fix uses one line of PHP code and so requires that your page has the .php
file extension.
This is a typical line in the head section to set the stylesheet:
<link rel='stylesheet' type='text/css' href='/path/style.css' />
Replace that with this:
<link rel='stylesheet' type='text/css' href='/style.css?<?php echo filemtime($_SERVER["DOCUMENT_ROOT"] . "/path/style.css"); ?>' />
So what does this do?
This PHP code appends the creation time of the file to the end of the file name in the form style.css?681239872
, the numeric value will change when you make a change to style.css
.
This tricks the browsers into thinking something is new so it’ll reload the style.css
file with the new changes and caches it until the next change.
This has saved me a lot of headaches and time while developing my site.
I share it with you and hope you find it useful.
Thanks.