Web browsers automatically save webpage stylesheets, JavaScripts, and other static files such as images and favicon on a user’s computer. This is called caching. Caching saves user time and bandwidth by not downloading the same files over and over again. It’s a great feature, but it also pose a big problem when a website makes some changes to a file. For instance, the webmaster may change some styles or JavaScript. Since the filename generally remains the same, a browser has no way of knowing it has been updated and uses old cached version of the files instead. To avoid this, browser needs to be notified when a file has been modified. Here are some ways to do so:
Manual Method
The simplest way of informing browser about a file modification is to change its name. This can be done by adding “ver” parameter to the filename. You can then increment the version number each time you want to force download a file. You can do it like this:
Force cached stylesheet to refresh:
<link href="http://sumtips.com/style.css?ver=2" rel="stylesheet" type="text/css" media="screen" />
Force cached JavaScript to refresh:
<script src="http://sumtips.com/script.js?ver=2" type="text/javascript"></script>
Force cached static files to refresh:
<link rel="shortcut icon" href="http://sumtips.com/favicon.ico?ver=2" />
You can add anything after the ‘?’ to force refresh files.
Automatically Using PHP
Updating version info manually each time may become tedious. To automate the process, we can use PHP to add the parameter:
<link href="http://sumtips.com/style.css?ver=<?php echo(filemtime("style.css")); ?>" rel="stylesheet" type="text/css" /> <script src="http://sumtips.com/script.js?ver=<?php echo(filemtime("script.js")); ?>" type="text/javascript" ></script> <link rel="shortcut icon" href="http://sumtips.com/favicon.ico?ver=<?php echo(filemtime("favicon.ico")); ?>" />
Now whenever the file is changed on the server, its modified time is added to filename. This lets the browser know that the file has changed and it downloads a new copy.
WordPress
On WordPress, you can add the time() function to the code that adds the stylesheet and JavaScript files to your theme:
wp_enqueue_style( 'theme_style', 'style.css', '', time() ); wp_enqueue_script( 'theme_script', 'script.js', '', time() );
via WPEngineer
Hope it helps!
One thought on “Force Refresh CSS, JavaScript & Any Static File in Browser Cache”
We’re a group of volunteers and opening a new scheme in our community. Your website provided us with valuable info to work on. You’ve done a formidable job and our whole community will be thankful to you.