Follow

Auto-clearing browser cache after deployments

Majority of web developers have had to, one time or the other, ask their users or the test engineer to clear their cache before validating a change. Browsers’ cache static resources like JavaScript and CSS, and load them from their cache to improve page load speed. Hence your latest modifications won’t apply until the end user clears their browser’s cache. We’ve been using a technique that allows us to refresh the browser cache automatically without asking our users to do so.

 This is how you usually load a CSS or a JavaScript file –

What we’ve done –

You’ll notice that we’ve added a new ver query string parameter. After deployment, we simply update the query string value to say 1.0.1. The browser sees a new URL and hence downloads the new file.
The value for the ver query string parameter can be taken from a global constant, that can be updated every time before a deployment.
The benefit of this technique lies in its simplicity, and the fact that you have to make no modification whatsoever to your server.

Handling this in WordPress

In WordPress we load our JavaScript and CSS using the predefined methods wp_enque_scripts and wp_enqueue_style. WordPress handles the tag and script URL generation, so how do we change the version number at the end of the script tag?
Luckily WordPress provides two filters that we can use to our advantage – script_loader_src and style_loader_src
Here’s the code to handle this –

In the refresh_browserCache method, we are replacing or appending the ?ver=VERSION to the script path. Before every deployment, we change the version number (VERSION). So when the HTML page to be sent to the browser is generated, it’ll be generated with this new version number. The browser sees the new URL and makes a request to the web server to fetch the file. Using this technique, we no longer have to ask our users to clear their browser cache to check a new feature.

About the author

Prasanna works at Osmosys as a PHP developer. She is a Computer Science Graduate from JNTU Vijayanagaram, with over 2 years of PHP and wordpress experience. You can find her on facebook @pulukurthi.prasanna

Are you interested? follow us and get notified of new posts

One thought on “Auto-clearing browser cache after deployments

  1. Suresh
    at 4:14 pm

    Nice Article.
    It’s a good way to make sure the cache is cleared.

Leave A Reply

three + 9 =