How can I tell whether a JavaScript file has already been included in an ASP.NET page?

Shimmy Weitzhandler picture Shimmy Weitzhandler · May 26, 2009 · Viewed 8.4k times · Source

I have an ASP.NET user control (.ascx file). In this user control I want to use a .js file.

So I include <script src="file.js" type"text/javascript"></script> on the page.

However, sometimes I use this user control in a webpage where this same script has already been loaded.

How can I add a <script /> declaration that will render on the page only if the page doesn't already contain another <script /> tag for the same script?

Answer

Neil Trodden picture Neil Trodden · May 26, 2009

As you are using asp.net, it makes sense to do the check server-side as that will be where you choose to add the reference to the javascript file. From your .ascx file you could register with the following:

this.Page.ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);

... from your page you just call the ClientScript object directly:

ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);

The 'GlobalUniqueKey' can be any string (I use the url of the javascript file for this too)

If you try to register a script with the same key string, it doesn't do anything. So if you call this in your page, your control or anywhere else, you'll end up with only one reference in your page. The benefit of this is that you can have multiple instances of a control on a page and even though they all try to register the same script, it is only ever done a maximum of one time. And none of them need to worry about the script being already registered.

There is a 'IsClientScriptIncludeRegistered(stringkey)' method which you can use to see if a script has already been included under that key but it seems pretty redundant to do that check before registering as multiple attempts to register do not throw exceptions or cause any other errors.

Doing the check client-side means that, assuming the multiple javascript references are cached by the browser (they may not be), you still have multiple tags and the over head of each one causing some javascript to run. If you had 20 instances of your control on a page, you could get serious issues.