Detecting out-of-date JavaScript libraries

A major challenge of writing rapid-changing AJAX applications is the asynchronous nature of browser page fetching. It's almost impossible to ensure that the browser will fetch the new version of all the components of your application (for example, JavaScript library) when it changes on the server.

You might solve this problem by renaming the JavaScript libraries (.js files) every time you make a significant change that could break the client-side application. While being bullet-proof, this approach requires republishing of all pages referencing the renamed library (which could be your entire web site).

It's way better to include the cache-checking code in your application:
  • Within your library, set a global variable (or a property of window object) to library's version number. The version number could be an increasing number, the date the change was made or (ideally) a version number from your source code control system (SCCS for Unix fans or Visual SourceSafe for Windows)
  • In every web page that relies on particular functionality of that library, check the version number and force a reload if there's a mismatch.
For example, in your JavaScript file, include a statement setting the version number ...
window.version_MyLibrary = 20060810; // library last changed on August 10th, 2006
... and at the beginning of the web pages requiring new library functionality, check the version number just after the library has been included with the <script> tag:
<script>if (window.version_MyLibrary < 20060810) location.reload(true);</script>
So, if your web page detects that the library included during the load process has an incompatible version number (due to cached version being used by the browser), it forces a hard reload, downloading all components from the web server.

No comments:

Post a Comment