Force refresh of CSS and JS files in WordPress

Ever work on a site and not see the latest style changes you made? The problem is likely that the browser is serving a cached version of your site. In order to see your latest changes, you’ll need to force a refresh of CSS and JS files, by instructing the browser not to load the cached version of the file.

Let’s back up and explain what caching is:

In computing, a cache is a hardware or software component that stores data so that future requests for that data can be served faster

So caching is basically a way to make the browser’s life easier by decreasing the amount of data it needs to receive and compute, by saving the files temporarily on the user’s computer. It also makes the user experience better because the user enjoys a faster load time on a website.

Caching is great. What’s the problem? 

If our site is using caching (like any live website should), changes  to our CSS and JS may not appear immediately because our browser does not know we have a new version of our CSS or JS file, Our browser will try to save time and resource by loading our old file from our saved cache.

Alert the browser when our cached files have been changed

What we want is to explain to the browser that there is a new version of a file and the browser should use that newer version and not the cached version.

Let’s have a look at our  wp_enqueue_script function, and  wp_enqueue_style, which are both used to load our CSS and JS files. Normally, you can expect to find them in a theme’s functions.php file. The function accepts 5 variables.

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer);

Lets focus on the 4th variable $var that controls the version number of the file.

We will use a small trick to force a new version number every time the file is saved so our browser can tell there is a new version of the file. we will use the PHP function filemtime() that supplies a number representing the last time the file was modified.

Copy the below code and modify as needed.

function Yourtheme_assets() {
	wp_enqueue_style( 'main', get_template_directory_uri() . '/css/style.css', array(), filemtime( get_stylesheet_directory() . '/css/style.css' ), 'all' );
	wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), filemtime( get_stylesheet_directory() . '/js/script.js' ), true );

}

add_action( 'wp_enqueue_scripts', 'Yourtheme_assets' );

Enjoy! 

Feel free to reach out with any questions!

Leave a Reply

Your email address will not be published. Required fields are marked *