• Home
  • Blog
  • 2019
  • October
  • Cache Busting in W3TC: How to force your visitors to see your theme’s updated JS and CSS files

Blog

Cache Busting in W3TC: How to force your visitors to see your theme’s updated JS and CSS files

 

Sometimes modifications to existing .js and .css files are not reflected for users visiting your website. This occurs because those files have been cached in the user’s browser from a previous visit and the cached version is served instead of the most recent version. The expiration of this cache is called time to live, or TTL and it is associated with this local cache in your browser, which is why it will show the old version until this length of time has passed. To see the correct version of the files, the user has to either clear the browser’s local cache & reload the page or do a hard refresh of the page by pressing Ctrl+F5 to ensure their browser is using the latest file versions.

When a user tries to access the URL, and the browser starts fetching the page data, it sees that it already has the page’s stylesheet E.G. style.css, and  says “Wait!, I already have this file cached, so I don’t need to fetch it again and can just present that to the visitor”. And the Browser has a point!

What is Cache Busting?

Asking each and every user to clear their browser cookies or do a hard refresh is not reasonable and leads to frustrating user experience. To remedy this, we can use a technique known as Cache Busting. Cache Busting works by appending a unique query string to the path of the .js or .css file that tells the browser there is a new file to add to the cache memory.  When the browser loads a page using these query strings it downloads any unrecognized files and displays them for the visitor.

How can I fix this?

You can use any unique query string you want to bust the browser cache, but the easiest way to guarantee a unique string is to use version numbers.

For example:

Let’s say you make some changes within your theme’s main JS file:

/mywebsite/wp-content/themes/mytheme/mytheme.js

After updating the file simply add a version number query string ?v=1.0

/mywebsite/wp-content/themes/mytheme/mytheme.js?v=1.0

This way when the browser will see the updated JS as a new .js file which is not cached. So it will generally force the browser to update the JavaScript/stylesheet. So, each time you update your JS/CSS on the server, you can incrementally update your version number so it busts the previously saved browser cache.

You can accomplish this when you enqueue your script by adding an argument for the version, for example:

 

Subscribe to W3 EDGE Updates

This entry was posted on and is filed under News. You can follow any responses to this entry through the RSS 2.0 feed.

No related posts were found

Comments are closed, but trackbacks and pingbacks are open.