Logic Story

February 8, 2013

Include Javascript files safely

Filed under: ASP.NET, CodeProject, JavaScript — Tags: , , — Cruz Boon @ 23:48

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 3 child folders for the simulation.

image

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

image

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

image

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");
            Page.Header.Controls.Add(script);
        }

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

image

image

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.

Download Attachment

About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Silver is the New Black Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: