Click here to Skip to main content
13,145,668 members (36,808 online)
Click here to Skip to main content
Add your own
alternative version


3 bookmarked
Posted 12 Feb 2013

Include JavaScript files safely

, 12 Feb 2013
Rate this:
Please Sign up or sign in to vote.
How to include JavaScript files safely.

Sometimes, you might accidently exclude JavaScript files because you were to use the method below to include JavaScript files.

<script language="javascript" src="Scripts/jquery-1.4.1.min.js" type="text/javascript" ></script>

Actually this method works most of the time. But if your project goes complicated and more modules are required to develop and you started to use Folder to group your pages. Here I use three child folders for the simulation.


Let check what will happen to the JavaScript file that I wish to include in NewPage.aspx.


When I inspect the javascript files by using FireBug, I cannot see it from the Script listing.


But it is available in Default.aspx.

To overcome this, I prefer to use code behind to include JavaScript files. Below is the code that I placed in the master page for this purpose.

protected void Page_PreRender(object sender, EventArgs e)
    System.Web.UI.HtmlControls.HtmlGenericControl script;

    script = new System.Web.UI.HtmlControls.HtmlGenericControl("script");
    script.Attributes["type"] = "text/javascript";
    script.Attributes["src"] = Page.ResolveUrl("~/Scripts/jquery-1.4.1.min.js?v=1");

As you expected, now both pages can have JavaScript file included.



script.Attributes["src"] = Page.ResolveUrl("~/Scripts/jquery-1.4.1.min.js?v=1");

You might curious why I included a query string at the end of the javascript file name. This is because during the development, JavaScript files change frequently. And my preferred browser – Firefox comes with a feature which will cache the JavaScript files. Most probably this is to has a better performance but it make the new version of my javascript cannot be render out. So this workaround allow me to trick the browser to always get the file from server whenever I change the “version” (v=1) number.

Hope this sharing make your JavaScript files render out safely.


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


About the Author

Cruz Boon
Team Leader Powercomp Software Sdn Bhd
Malaysia Malaysia
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 12 Feb 2013
Article Copyright 2013 by Cruz Boon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid