Web Dev Gotchas: Javascript Changes Not Showing Up

This is a problem that every new web developer will run into. You modified your JavaScript file but the changes don’t show up on the browser. So you hit F5 a bunch of times, double-checked that you really saved the file, and still nothing. Looks like your browser randomly decided to use the cached version of your JavaScript file.

Browsers cache resources, such as JavaScript, CSS, and images, to speed up subsequent page loads for users. However, sometimes the browser serves stale resources to the user, even though the resources have changed on the web server. This may happen if the target page, “index.php”, for example, did not change, but its external JavaScript resource “myjavascript.js” did. The browser may (unpredictably) assume that if “index.php” is the same as the cached version, its linked resources should be the same. We, developers, want our users or customers to utilize our latest updates.

This caching issue is hard to reproduce because each browser’s caching scheme is different and the implementation is a black box to us. There are no explicit built-in mechanisms to handle this exact issue. However, the workarounds are pretty simple.

Option 1. Disable caching for yourself so that this issue does not affect you while you code. In Chrome, for example, caching could be turned off in Chrome’s built-in “Developer Tools”, under the Network tab. When it is time to release to your production site, add a version number to your JavaScript file i.e. “myjavascript1.2.js”. This ensures that browsers see the file as new. The problem with this approach is the hassle of applying and managing the version number.

Option 2. In PHP, as well as any other server-side language, this could be accomplished by adding the file’s last modified timestamp to the src attribute.

<script src='/myjavascript.js?<?=filemtime('myjavascript.js')?>'></script>

Sample Output:
<script src='/myjavascript.js?1672986689'></script>

Leave a Comment

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

Scroll to Top