Click here to Skip to main content
11,412,833 members (73,545 online)
Click here to Skip to main content

How to Add JS Version before referencing JS file to the Page

, 31 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Updating referenced scripts realtime

Introduction

We always encounter a problem when it comes to the latest code deployed on our servers.  The page cached the javascripts thus making our updates on the scripts does not immediately take effect.

Background

The approaches below will give you an idea on how to make our pages know that there was already an updated version of the script and should be evaluated immediately by the page.  We should also take in consideration of the page' performance that's why we will going to use the global localstorage for some of the approaches.

First Approach

This approach will be suitable for the page with code behind.

On the aspx markup, reference your CSS or JS files like this:

<link rel="stylesheet" type="text/css" href="<%=AppendVersion("/Styles/myCSS.css")%>" /> 

On the aspx code behind, add the following code:

Public Shared Function AppendVersion(ByVal filePath As String) As String 
        Dim fileInfo As FileInfo = New FileInfo(Current.Request.MapPath(filePath)) 
        Dim cacheVersion As String = fileInfo.LastWriteTime.ToFileTime.ToString 
 
        Return filePath & "?v=" & cacheVersion 
End Function

Second Approach

This approach will be suitable for the page without code behind.  In addition, we are going to use the window localstorage. The snippet for detecting the local storage below was from Mathias Bynens from this article.

On the aspx markup, add the script:

<script type="text/javascript"> 
//Start snippet detecting the global localstorage
var storage = (function() { 
      var uid = new Date, 
          storage, 
          result; 
      try { 
        (storage = window.localStorage).setItem(uid, uid); 
        result = storage.getItem(uid) == uid; 
        storage.removeItem(uid); 
        return result && storage; 
      } catch(e) {} 
    }());
//End of snippet

var cached = function(name,value) { 
   if(storage.getItem(name) != null){ 
      return (storage.getItem(name).indexOf(value) >= 0)? true : false ; 
   }else{return false;} 
}; 

var GetFile = function(path) { 
        return path.substring(path.lastIndexOf('/')+1); 
    }; 
var execScript = function (script) {
        //locally created function
        var newfunction = new Function(script);
        newfunction();
    };
function RefJSVersioning(objUrl){ 
    var req = new XMLHttpRequest(); 
    req.open('HEAD', objUrl, false); 
    req.send(null); 
    var headers = (Date.parse(req.getResponseHeader('Last-Modified'))/10000).toString().split('.')[0]; 
    var source = objUrl + '?' + headers; 
    var fn = GetFile(objUrl); 
    if (storage) { 
      if(storage.length > 0){ 
         if (!cached(fn + 'source',source)){ 
            req = new XMLHttpRequest(); 
            req.open('GET', objUrl, false); 
            req.send(null); 
            storage.removeItem(fn + 'source'); 
            storage.removeItem(fn + 'content'); 
            storage.setItem(fn + 'source', source); 
            storage.setItem(fn + 'content', req.responseText); 
            execScript(req.responseText); 
         }else{ 
            execScript(storage.getItem(fn + 'content')); 
         } 
      }else{ 
         req = new XMLHttpRequest(); 
         req.open('GET', objUrl, false); 
         req.send(null); 
         storage.setItem(fn + 'source', source); 
         storage.setItem(fn + 'content', req.responseText); 
         execScript(req.responseText); 
      } 
    } 
};  

</script>

How to use:

<script type="text/javascript"> 
    RefJSVersioning("/Scripts/myScript.js");
</script>

Screenshot of the script stored on Local Storage:

This approach also works with pages displayed inside an i-frame.

 

History

Updated code to not using eval() to lessen the memory usage. Added new function "execScript".

Updated header value for precise modified time. Instead of dividing with 100,000, it was changed to 10,000.

Updated Screenshot and Added screenshot on how to debug scripts from local storage

Created Article July 31, 2014

Reference

Detecting local Storage : http://mathiasbynens.be/notes/localstorage-pattern

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Junell Zenarosa
Software Developer (Senior)
Philippines Philippines
"Always debugging those undisputed bugs" Smile | :)
Follow on   Google+

Comments and Discussions

 
GeneralMy vote of 1 Pin
Per Oestergaard at 5-Aug-14 3:38
memberPer Oestergaard5-Aug-14 3:38 
GeneralRe: My vote of 1 Pin
Junell Zenarosa at 5-Aug-14 21:41
professionalJunell Zenarosa5-Aug-14 21:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150427.1 | Last Updated 31 Jul 2014
Article Copyright 2014 by Junell Zenarosa
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid