CSS Adventures: Using filemtime to avoid caching
I started building websites in the early 2000s and most websites would be updated with: “refresh if you can’t see the new layout”. Because some browsers cached CSS like a demon, you would have to force (or in this case, invite) users to clear their cache manually to be able to see updated code.
I usually left it up to the users’ browsers/machines to magically return the most updated CSS and didn’t think about combatting this issue on my own websites until recently. Renaming the file to something like
style-v2.css was a common hack and certainly not the most ideal.
If your file is in PHP, you can use the function
filemtime to attach a timestamp to the end of your CSS file.
<link rel="stylesheet" href="style.min.css?<?php echo date('Ymd', filemtime('style.min.css')); ?>" type="text/css" media="screen">
Ymd can be altered to any PHP date values in any order you prefer, and can go as specific as seconds if you feel you really need it. If you own a small site and update your CSS only once a day,
Ymd should be enough. You need to update the value in
filemtime to reflect your own file name.
You can also manually change the value behind the question mark to a new number each time you update your CSS. This is obviously quite easy to follow, but I chose to use a date to allow it to be taken care of automatically.
If you use
filemtime, you can have the date as part of the file name itself:
style.<?php echo date('YmD', filemtime('style.css')); ?>.css
I’m using WordPress for my blog, so my current code is something like this. I call my stylesheet using the
bloginfo('template_url'), then pull the directory of the stylesheet along with its file name to generate the last modified date.
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/style.min.css?<?php echo date('Ymd', filemtime( get_stylesheet_directory() . '/style.min.css' )); ?>" type="text/css" media="screen">