Dynamic Script Replacement

Making sure that a JavaScript that is frequently updated doesn't get cached is best done by simply updating the headers for the particular JavaScript file. By doing that you can make sure that the script gets downloaded every time someone visits a page that references it. That takes care of the generic situation where the script can change reasonably rapidly over time where you want to make sure that they always collect the latest version.

Where you want better control over the script changes and don't mind having to manually edit the HTML of the pages that reference the script you can incorporate a version number into the file name of the script. Then by simply updating the references in the HTML to point to the new version you make sure that the latest version of the script will be downloaded when your visitors pick up the updated version of the page.

Where the script gets updated so frequently that it may change several times during a single visit to the page a different solution is required. Where the script is constantly changing we can set up JavaScript within the web page itself that will reload the script from the browser at regular intervals and so ensure that any changes to the script will be applied in web pages within seconds even if the page itself was opened before the script was changed. We do this by using a setInterval call that replaces the entire script tag in the web page every so many seconds. Every time we add a new script tag to the page via JavaScript the script that the tag references gets attached to the page. If the exact script specified is not cached then that script also gets downloaded from the server. We can force the download in this instance by adding a querystring to the end of the script name that will always have a different value to the ones used previously.


This same approach can be used where you want to be able to dynamically replace scripts at set time intervals during a visit to the page. You could use this technique to switch the particular file that contains the script to be run between two (or more) alternative versions of the same function. I can't see any particular use for this since a simpler solution would be to give the two functions different names and include them in the same script and then simply change which function gets called rather than swapping out the entire script but this did make it easier to test the functionality of the script to ensure that it will work for reloading the same script at specified intervals without having to actually modify the script quickly between calls.


You can see how this second variant works by clicking here a few times. The two different JavaScript files contain two slightly different versions of the a() function called from the link.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow