Click here to Skip to main content
13,289,626 members (59,195 online)
Click here to Skip to main content
Add your own
alternative version


2 bookmarked
Posted 9 May 2013

Include JavaScript Files with Automatic Versioning

, 9 May 2013
Rate this:
Please Sign up or sign in to vote.
Versioning file inclusion JavaScript by date of last modification


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:




The result will be the following line in our page:

<script language="'javaScript'" type='text/javascript' 



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


About the Author

Hernán Hegykozi
Team Leader
Argentina Argentina
No Biography provided

You may also be interested in...


Comments and Discussions

Suggestionmisleading title Pin
Seishin#9-May-13 22:31
memberSeishin#9-May-13 22:31 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 9 May 2013
Article Copyright 2013 by Hernán Hegykozi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid