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

僤鯓⒐⒋嵵緔 提交于 2019-11-30 18:22:45

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.

mysomic

You can do one of two things client side...

  1. Check the dom for the script tag corresponding to the javascript file your want to check
  2. Test a variable or function you know has/will be defined within the javascript file for undefined.

Here's a quick JS function which uses JQuery to do what you need:

function requireOnce(url) {    
    if (!$("script[src='" + url + "']").length) {
        $('head').append("<script type='text/javascript' src='" + url + "'></script>"); 
    }
}

use something like the following:

if(typeof myObjectOrFunctionDecalredInThisScript != 'undefined') {
  // code goes here
  var myObjectOrFunctionDecalredInThisScript = { };
}

This tests if your object or function already exists and thus prevents redeclaration.

var storePath = [];
function include(path){
if(!storePath[path]){
    storePath[path]= true;
    var e = document.createElement("script");
    e.src = path;
    e.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
    return false;
 } }

use this in your main page and call function include with argument javascript file name

Priyank Sheth

As you want to include javascript on one page of your site only.
If you use Asp.net(4.0) then it is very easy.
Just include following code

<script type="text/javascript" scr="filepath and name here"></script>

in ContentPlaceHolder of content page.

@Shimmy I am coming across this after a long while but maybe it might still be useful or at least help other coming from behind. To check if jquery is already loaded do this

<script>window.jQuery || document.write('<script src="js/libs/jquery-1.x.x.min.js"><\/script>')</script>

Don't miss the escape character in the closing script tag in document.write statement.

@mysomic, why did I not think of that. thumbs up

PS: I would have loved to write this right under the line where @Shimmy wrote that jQuery itself is the script he wants to load. But dont know how to write it there. cant see a reply or anything similar link. This may sound dumb but maybe I'm missing something. Pls point it out, anybody?

BornToCode

If you need it from server side, and Page.ClientScript.RegisterClientScriptInclude won't work for you in case script was included by some other way other then Page.ClientScript.RegisterClientScript (for example page.Header.Controls.Add(..), you can use something like this:

static public void AddJsFileToHeadIfNotExists(Page page, string jsRelativePath)
{
    foreach (Control ctrl in page.Header.Controls)
    {
        if (ctrl is HtmlLink htmlLink)
        {
            if (htmlLink.Href.ToLower().Contains(jsRelativePath.ToLower())) return;
        }
        if (ctrl is ITextControl textControl
          && (textControl is LiteralControl || textControl is Literal))
        {
            if (textControl.Text.ToLower().Contains(jsRelativePath.ToLower())) return;
        }
        if (ctrl is HtmlControl htmlControl)
        {
            if (htmlControl.Attributes["src"]?.ToUpper()
              .Contains(jsRelativePath.ToUpper())) return;
        }
    }

    HtmlGenericControl Include = new HtmlGenericControl("script");
    Include.Attributes.Add("type", "text/javascript");
    Include.Attributes.Add("src", page.ResolveUrl(jsRelativePath));
    page.Header.Controls.Add(Include);    
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!