65.9K
CodeProject is changing. Read more.
Home

Include JavaScript Files with Automatic Versioning

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

May 9, 2013

CPOL
viewsIcon

16833

Versioning file inclusion JavaScript by date of last modification

Introduction

In this tip, I would like to share how to prevent your browser from caching an older version of a JavaScript file included in a page.

You can set starting on the page that the browser not cache, but doing so is not optimal, because each time you load, the page will download the JavaScript file.

Using the Code

Let versioning file include JavaScript by date of last modification.

For this, we will need a method to perform this versioning LoadScript.

public static string LoadScript(string url)
{
	string strFilePath = null;
	strFilePath = HttpContext.Current.Server.MapPath(url);
	DateTime dtLastModified = System.IO.File.GetLastWriteTime(strFilePath);
	return "\n<script language="'javaScript'" 
	type='text/javascript' src='" + url + "?v=" + 
	dtLastModified.ToString("yyyyMMddhhmmss") + "'></script>";
} 
  • HttpContext.Current.Server.MapPath gets the actual path of the JavaScript file
  • System.IO.File.GetLastWriteTime allows for the modification date of the file
  • dtLastModified.ToString ("yyyymmddhhmmss") becomes the modified date on a string of numbers unique

This method receives the JavaScript file path to include, and returns the HTML needed to be so, by concatenating the variable "v", which contains the last modification date.

The usage is the following:

Response.Write(LoadScript("/Scripts/demo.js"));

or:

<%=LoadScript("/Scripts/demo.js")%> 

The result will be the following line in our page:

<script language="'javaScript'" type='text/javascript' 
src='http://www.codeproject.com/Scripts/demo.js?v=20120403053547'></script>