Force Refresh CSS, JavaScript & Any Static File in Browser Cache

Print Page

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="" rel="stylesheet" type="text/css" media="screen" />

Force cached JavaScript to refresh:

<script src="" type="text/javascript"></script>

Force cached static files to refresh:

<link rel="shortcut icon" href="" />

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="<?php echo(filemtime("style.css")); ?>" rel="stylesheet" type="text/css" />
<script src="<?php echo(filemtime("script.js")); ?>" type="text/javascript" ></script>
<link rel="shortcut icon" href="<?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.


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”

Comments are closed.