Introduction

It is common for ASP.NET developers to adopt lax practices in their management of JavaScript. I believe this is because there is not a lot of reliable information online for how to properly deal with JavaScript in an ASP.NET application. The purpose of this article is to present an optimal technique to manage your JavaScript in your ASP.NET applications. The following issues will be addressed:

Prerequisites

Make sure you have Visual Studio 2010. Some concepts presented in this article may not work with the Express editions.

Overview

Most of the above problems are caused by placing JavaScript or references to JavaScript files directly in the ASPX page. The solution to almost all of the above problems is to use ASP.NET's built-in capability to embed JavaScript files into a DLL and then reference those files dynamically. This article will present those capabilities, as well as some techniques to take full advantage of them. A tutorial format will be used to explain how each step is done.

Getting Started

First things first. Start up Visual Studio 2010 and create a new empty web application called ParchmentPurveyor (we are making a website for somebody who wants to sell fancy paper):

Now, add a new web form called "Default.aspx", and add some simple HTML to it. It should look something like this:

Adding JavaScript

Now that we have a fully functional website that is sure to get the attention of a plethora of people, we can focus on the JavaScript coding. Rather than add a JavaScript file to our main project, we will do things a little differently. We are going to create a new project to hold all of our JavaScript files. Start by adding a new class library project, called JavaScriptLibrary, to the solution:

When you added that project, a file called "Class1.cs" was added for you. We don't need that, so delete it. Add a folder to JavaScriptLibrary called "JavaScript". You will also add two JavaScript files to that folder. Call them "ShowMessage.js" and "GreetUser.js". Next, create a new class called JavaScriptHelper (do not place this in the "JavaScript" folder... it will go at the root level of the JavaScriptLibrary project). By now, your solution structure should look something like the following:

A couple of empty JavaScript files aren't going to do us any good, so let's put something in them. For starters, "ShowMessage.js" will hold a function called ShowMessage():

function ShowMessage(msg) {
alert("Message From Website: " + msg);
}

The "GreetUser.js" file will have its own function, GreetUser():

function GreetUser() {
ShowMessage("Greetings and Salutations!");
}

Notice that GreetUser() is dependent upon ShowMessage(). We will be handling that later.

Embedding the JavaScript Files

Rather than have to deploy our JavaScript files to our website, we'd like them to be embedded into the DLL. That way, if the DLL is deployed to the website, all JavaScript files are also automatically deployed. Doing this is very simple; all we need to do is go to the properties for each JavaScript file and change the "build action" from "content" to "embedded resource":

While that will ensure the files get embedded into the DLL, you must still make them available to the web client. Before you do that, the JavaScriptLibrary project needs to reference System.Web:

Once you have added that reference, edit "JavaScriptHelper.cs" by adding the following using statement and assembly attributes:

That will enable your embedded JavaScript files to be accessible from the client computer.

Including the Embedded JavaScript Files

Now that you have embedded the JavaScript files and made them accessible via the client computer, you must actually reference them from the pages they are used on. To facilitate this, we will fill in our JavaScriptHelper class:

The IncludeJavaScript() function is what does all the magic. It ensures a script tag gets inserted for an embedded JavaScript file, which it does by calling RegisterClientScriptResource(). IncludeJavaScript() is called by Include_GreetUser(). Notice also that Include_GreetUser() calls Include_ShowMessage(), which means it handles dependencies for the user of the class. Any page that includes the GreetUser() function will also include the ShowMessage() function.

Now that we have that class available for our use, let's put it to use on the "Default.aspx" page. You can start by making sure ParchmentPurveyor has a reference to JavaScriptLibrary:

Next, we'll need to modify the code behind to include the JavaScript on the page.

Finally, we just have one thing left to do -- call the GreetUser() function from the page. To do this, all we need to do is add the following JavaScript to the page (I chose to add it in the head tag):

Notice there are two script tags that reference something called "WebResource.axd". That is basically a service which serves embedded information to the client. You can read more about "WebResource.axd" here. The important thing to note is that the first script tag is serving up the ShowMessage() function and the second script tag is serving up the GreetUser() function. Both of those script tags were included in the page when you called the Include_GreetUser() function in your JavaScript library.

Late Includes

Sometimes, the above technique does not include the JavaScript file. For example, I work with a third-party tool that prevents me from calling .NET code before the render stage. When you call the include functions above during the render stage, the script tags do not get inserted into the page. This is because the beginning of the page has already been rendered to HTML. My solution to this problem is to create an alternate form of the function that inserts the script tag near the bottom of the HTML. I call this a "late include". We can support this technique with a few changes to JavaScriptHelper:

I modified each method to accept an additional parameter, late. This defaults to false, so the methods can still be called the same way they used to be. A value of false will preserve the old behavior. A value of true will cause the script blocks to be included near the end of the HTML. Note also that in the case that late is false, I still call RegisterStartupScript(), but I pass it an empty string (so that function call does not actually insert anything into the HTML). This is done so IsStartupScriptRegistered() will return the correct value. That way, the JavaScript will never be included more than once, even if one of the functions is called with late set to false and then again with late set to true. If you want to see this in action, comment out the OnPreRender() in the code behind and modify the body of the page to look like this:

<body><formid="form1"runat="server"><h1>Parchment Purveyor</h1><p>Paper for printers, painting, publication,
paper planes, and plenty of other plebeian projects!</p><% // This gets called during the render stage.
JavaScriptLibrary.JavaScriptHelper.Include_GreetUser
(Page.ClientScript, true); %></form></body>

That will call the version of the function that includes the script tags near the bottom of the HTML, which you can observe by viewing the source of the page when you run the application.

External JavaScript

So far, I've only demonstrated how to include embedded JavaScript. However, it is sometimes desirable to link to an external JavaScript file. To facilitate this, we need to add a new helper function in JavaScriptHelper:

As an example of an external file you might include, I'll use the jQuery file hosted by Microsoft's CDN. Just like the other JavaScript files, you will create a function in JavaScriptHelper to include jQuery on the page:

Adding New JavaScript Files

Once you have everything setup, there are only a few steps you need to complete when adding new JavaScript files:

Add the ".js" file to the "JavaScript" folder. Skip this step for external JavaScript files.

Set the "build action" to "embedded resource". Skip this step for external JavaScript files.

Add the assembly attribute to indicate the JavaScript file is a web resource. Skip this step for external JavaScript files.

Create a function in JavaScriptHelper to include your JavaScript file.

Call the function you just created from a page, control, or masterpage.

Excluding JavaScript Files

While you should have everything you need to include JavaScript, you must sometimes exclude JavaScript. For example, when working with third-party control libraries that may have exotic ways of including JavaScript, the only way to prevent a certain JavaScript file from being included twice may be to have your code avoid including it (and let the third-party library include the JavaScript for you). This can be accomplished with one more helper function. Before we get to that, however, let's demonstrate a scenario where this technique will come in handy. Say your third-party control includes jQuery. This user control, "InlineGreeting.ascx", will serve as just such a control:

<%@ Control Language="C#"%><%-- This is a bad way to do things, but we can luckily overcome this obstacle. --%><scripttype="text/javascript"src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script><scripttype="text/javascript">
$(document).ready(function() {
$("#lblGreeting").text("Hello");
});
</script><p><labelid="lblGreeting"></label></p>

Now suppose we have another control, "Hello.ascx", that uses that same jQuery file:

Now, if we were to include both of our user controls on the "Default.aspx" page, jQuery would get included twice (once by the third-party control and once by our JavaScript library). In order to avoid that, we will add two functions, ExcludeJavaScript() and Exclude_jQuery(), to our JavaScriptHelper class:

Notice we have defined a new constant, NAME_DUMMY_FILE. The above functions assume we have added an empty JavaScript file to our "JavaScript" folder and embedded it according to the above instructions. This empty dummy JavaScript file will be included in place of any JavaScript files we want to be excluded. All we need to do in order to prevent our library from including jQuery is to call Exclude_jQuery() from the Page_Load() of "Default.aspx":

// Page load occurs before pre-render (the ideal place to exclude JavaScript).
protectedvoid Page_Load(object sender, EventArgs e)
{
// We have some third-party control that includes jQuery in a weird way,
// so we will avoid including it again.
JavaScriptLibrary.JavaScriptHelper.Exclude_jQuery(Page.ClientScript);
}

Now all we need to do is modify "Default.aspx" to include "InlineHello.ascx" and "Hello.ascx" and we are done:

Now that we have made sure to call Exclude_jQuery() before Include_jQuery(), we have prevented our JavaScript library from including "jQuery.js". That way, jQuery is only included once by our mock third-party control. Most of the time, this situation should be avoidable. However, for when it is not avoidable, this technique should tidy up our HTML output nicely.

A Note For VB.NET Users

When making the VB.NET version of the code, most everything was the same as the C# version, aside from syntax differences. However, there was one important gotcha you should keep in mind. In the C# version of the code, you'll note that all the paths to the JavaScript files start with "JavaScriptLibrary.JavaScript.". However, in the VB.NET version of the code, all the paths start with only "JavaScriptLibrary." (i.e., VB.NET seems to ignore the "JavaScript" folder all of the JavaScript files are in). That requires VB.NET users to make just a few changes:

Aside from that, I found no other differences when making this code work in VB.NET. If you would like to try it yourself, the VB.NET version of the code can be downloaded using the link at the top of the article.

What Did You Gain?

After all this work with the same apparent HTML output, you might be asking yourself, "what did I really gain by adding all this extra code?" Well, here are a few solutions presented by this approach:

Deploying JS - You do not need to include the ".js" files when you deploy your web application. Deploying the DLL will be enough.

Bad References - Even if you change the path of your application, you will not have to worry about changing your JavaScript paths.

Dependencies - Dependencies are managed automatically. If you included "GreetUser.js", "ShowMessage.js" will automatically be included.

Unused JS - No JavaScript is included on the page unless you call the function to include it. This will avoid having unused JavaScript on the page (potentially speeding up load times for users).

HTTP / HTTPS - The code outputs script tags that do not include the protocol, so the protocol should be the same as the current page (i.e., HTTP or HTTPS).

Refactoring - If you want to use a different version of a script, you only need to modify it in one place. This could be useful, for example, if you decide to switch to a CDN version of jQuery rather than hosting it yourself. It could also be useful for upgrading to a new version of jQuery.

Redundancy - No matter how many times you call one of the include functions, the script tags will only be included on the page once.

History

2014-09-21: Fixed typo

2011-11-10: Removed linked URL from the PRE tags

2011-05-29: Fixed the URLs in the PRE tags that the Code Project article editor mangled

2011-05-25: Added VB.NET download, as well as a section about the VB.NET version, and made some minor changes to the C# download