1

I have a situation where I'd like to add a "last modified" timestamp to the paths of my js files (ex. "custom.js?2009082020091417") that are referenced in my ScriptManager (contained in my MasterPage) and in any ScriptManagerProxies (content pages).

I can easily get access to the ScriptManager in code and then iterate through it's Scripts collection to get the Script paths that I've set declaratively and then "set" a new path with the tacked on "?[lastmodifiedtimestamp]".

The problem is, I can't figure out how to get to any ScriptManagerProxies that may exist.

When debugging, I can see the proxies in the non-public members (._proxies). I've looked through the documentation and can't see where you can actually publicly access this collection.

Am I'm missing something?

I have the following code in the base class of my content page's Page_PreRenderComplete event:

ScriptManager sm = ScriptManager.GetCurrent((Page)this);
if(sm != null)
{
     foreach (ScriptReference sr in sm.Scripts)
     {
         string fullpath = Server.MapPath(sr.Path);
         sr.PathWithVersion(fullpath); //extension method that sets "new" script path
     }
}

The above code gives me the one script I have defined in my MasterPage, but not the two other scripts I have defined in the ScriptManagerProxy of my content page.

1 Answer 1

4

Came up with a solution. Seems that the only place that all the merged scripts can be accessed is in the main ScriptManager's ResolveScriptReference event. In this event, for each script that has a defined path, I use an extension method that will tack on a "version number" based on the js file's last modified date. Now that my js files are "versioned", when I make a change to a js file, the browser will not cache an older version.

Master Page Code:

 protected void scriptManager_ResolveScriptReference(object sender, ScriptReferenceEventArgs e)
 {
    if (!String.IsNullOrEmpty(e.Script.Path))
    {
        e.AddVersionToScriptPath(Server.MapPath(e.Script.Path));
    }
 }

Extension Method:

 public static void AddVersionToScriptPath(this ScriptReferenceEventArgs scrArg, string fullpath)
 {
       string scriptpath = scrArg.Script.Path;

       if (File.Exists(fullpath))
       {
           FileInfo fi = new FileInfo(fullpath);
           scriptpath += "?" + fi.LastWriteTime.ToString("yyyyMMddhhmm");
       }

       scrArg.Script.Path = scriptpath;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm for JS, but how do (would?) you handle WebResource files associated with your Javascript (e.g. CSS, images, etc.)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.