views:

27

answers:

2

I have a .NET web applications which uses a lot of javascript. The .aspx and the .js files go hand-in-hand together. Problem: The .aspx files are always up-to-date on the client (not cached) but the .js files might well be cached. This is even a problem if the files are only cached for one session since users are spending many hours on my site and everytime I update a .aspx/.js pair users are running into a problem.

Now, I found a solution but I am not sure if there is perhaps a better solution or if my solution has a performance drawback.

This is my solution:

.js-References in .aspx:

<script type='text/javascript' src='../scripts/<%# GetScriptLastModified("MyScript.js") %>'></script>

So, the "GetScriptLastModified" will append a ?v= parameter like this:

protected string GetScriptLastModified(string FileName)
{
  string File4Info = System.Threading.Thread.GetDomain().BaseDirectory + @"scripts\" + FileName;
  System.IO.FileInfo fileInfo = new System.IO.FileInfo(File4Info);
  return FileName + "?v=" + fileInfo.LastWriteTime.GetHashCode().ToString();
}

So, the rendered .js-Link would look like this to the client:

<script type='text/javascript' src='/scripts/GamesCharts.js?v=1377815076'></script>

The link will change every time, when I upload a new version and I can be sure that the user immediately gets a new script or image when I change it.

A: 

Just a thought: You could probably just render the JS as an ASPX; I've done this for forceful reload of CSS before with a JSP. Not proud of that solution, but it's worked before.

<script type='text/javascript' src='/mycode/GamesCharts.js.aspx'></script>

Then just render the JS statically in the ASPX file.

JustinShoffstall
If you're doing this, might as well configure your web server to serve js files as non-cached.
slebetman
Absolutely; that's the right way to go if you want all of your JS dynamic. However, if you only have a few files that must be uncached, the above method works.
JustinShoffstall
Well my .js files change once every few weeks. I do not want them to be totally dynamic. No way. I even configured my webserver with a no-expiry tag. But SOMETIMES they DO change and then I need a mechanism to force an update.
newtogit
+1  A: 

Safari refuses to cache URLs with query parameters. So instead of a query parameter you can use something like a versioned path and use mod_rewrite to remove it.

Something like:

<script type='text/javascript' src='/scripts/1377815076/GamesCharts.js'></script>

And in Apache config file (config for other servers left as homework):

RewriteEngine On
RewriteRule  ^/scripts/[0-9]+/(.+)$    /scripts/$1
slebetman