web development – Solution to notify users Single Page Application (SPA) static resources have updated if users don’t refresh their browsers

Basically you want to trigger an event when the version changes to inform the user that their UI is outdated and they should refresh. If you want to keep it simple this can be done file-based. You basically need these components:

  • A JavaScript file (currentversion.js) that dispatches a event about the current version
  • Logic in the SPA that periodically reloads currentversion.js file and defines listeners for the “currentversion” event.

The generation of that currentversion.js and currentVersion can be automatically generated to contain the correct version on every build.

The idea is to (re)load the currentversion.js as needed to dispatch the current version of the UI. The logic can listen for that event and act when the version has deviated from last known version.

In theory you can have something like:

currentversion.js

window.dispatchEvent(new CustomEvent('currentversion', { detail: '1.1' }));

index.html

<html>
    <body>
        <script>
            const currentVersion = '1.1';
            
            function startVersionCheck() {
                const versionJs = document.getElementById('version-js');
                const versionJsUrl = versionJs.src;
                let versionJsReloadCount = 0;
                const versionCheck = function () {
                    versionJs.src = (versionJsUrl, '?rc=', ++versionJsReloadCount).join('');
                };
                setInterval(versionCheck, 60000);
            }

            window.addEventListener('currentversion', function (e) {
                const version = e.detail;
                if (currentVersion !== version) {
                    window.dispatchEvent(new CustomEvent('versionchanged', { detail: version }));
                }
            });

            window.addEventListener('versionchanged', function (e) {
                alert('New UI version available!');
            });

            window.addEventListener('load', startVersionCheck);
        </script>
        <script id="version-js" src="./currentversion.js"></script>
    </body>
</html>

Both the UI and currentversion.js expose the same version initially. When the value changes in currentversion.js it should eventually trigger the versionchanged event on the next reload.

Once the user reloads both version are in sync again.