How do you bypass browser cache on a new web app update?

twitter logo ・1 min read

When releasing a new web app update, browser caching can be a problem.

For example, if you update the script.js and if the user's browser still loads that script from the cache, the app can crash.

When I searched this on Google, I found several ways to prevent this like:

  • Using cache headers
  • Using GET params with the script's URL
  • And more...

I would like to know what is the best way according to your thoughts.

Thanks.

twitter logo DISCUSS (4)
markdown guide
 

The method that I am using currently is to add a version or build number suffix to your script.js. ex: script-1.0.0.js. You can automate this using your favorite task runner whenever you create a new build - npm, grunt, etc.

 

So, do you edit the HTML file every time?

I mean, the <script> tag's src.

Or...?

 

What tech stack are you using for your app? There are a number of methods available but they depend on your stack. Here are some examples:

NPM
You can use npm to build your js file, concatenate, minify, etc. If you have a package.json, you may have a version property in it. When you run your build script, you can make reference to that version property. Here is an excerpt from my package.json file.

{
  "version": "1.0.0",
  "scripts": {
    // use rollup module to bundle all of my ES modules and create a new file
    // inside a /dist folder. I make reference to the version number using 
    // %npm_package_version%
    "bundle-es": "rollup public/js/main.js --format cjs --name 'js-bundle' --file public/dist/%npm_package_version%/js/main.js"
    "build": "npm run bundle-es"
}

Dynamic
If you are using a server-side language like PHP, .NET, Ruby, etc, you can output the script tag using the server-side language, but first read a version.txt file. Example:

#version.txt
1.0.0

Then use your server-side language to read that .txt file, to get the version. Then use server-side language to output the script tag for you.

<?php
$version = file_get_contents('/version.txt', true);
echo '<script src="script.js?v=' . $version . '"></script>';
?>

Thank you!

I was using the second approach. It works quite well.

Classic DEV Post from Apr 1

How I Write Online Articles

How you can write online articles

Supun Kavinda profile image
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.

Signed up yet?

DEV is one of the most important resources in software.

Create Your Account