简体   繁体   English

检查javascript是否已附加到页面?

[英]Check if javascript is already attached to a page?

Is there any way to check if javascript file is already attached to the page by its file name. 有没有办法检查javascript文件是否已通过其文件名附加到页面。

For eg : 例如:

if ("path-to-script/scriptname.js") already embeded
{
call related function
}
else
{
Append '<script src="path-to-script/scriptname.js" type="text/javascript"> </script> '
call related function
}

Basically I dont want 1 script to be attached twice on the same page. 基本上我不希望在同一页面上连接两个脚本。

You'd need to test whether the actual function from the script file exists, like this: 您需要测试脚本文件中的实际函数是否存在,如下所示:

if (window.function_name) {
    // script loaded
} else {
    // script not loaded
}

You might not always know what objects or functions a script contains in advance, in such cases you can search for script tags containing the desired src. 您可能并不总是事先知道脚本包含哪些对象或函数,在这种情况下,您可以搜索包含所需src的脚本标记。

With jquery: 使用jquery:

$("script[src*='"+scriptName+"']");

Without jquery: 没有jquery:

document.querySelector("script[src*='"+scriptName+"']");

I agree with @zathrus though I think you should be using requirejs for things like this. 我同意@zathrus虽然我认为你应该使用requirejs来做这样的事情。 The idea is that dependencies must be fetched before executing the code. 这个想法是必须在执行代码之前获取依赖项。 The above method you are using may work but you can not guarantee anything. 您正在使用的上述方法可能有效,但您无法保证。

RequireJS will beautifully maintain all the dependency loading. RequireJS将精美地维护所有依赖性加载。 It is very easy to learn as well. 这也很容易学习。

Simply check if the library is defined, otherwise import it: 只需检查库是否已定义,否则将其导入:

if ( !jQuery ) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    document.body.appendChild(s);
    s.src = "path-to-script/scriptname.js";
    void(0);
}
// call function

you really need a script loader.. because as you said you want it specific with the javascript resource filename and this is sort of your javascript files are depending to each other 你真的需要一个脚本加载器..因为正如你所说,你想要它具体的javascript资源文件名,这是你的javascript文件是相互依赖的

www.headjs.com www.headjs.com

www.modernizr.com www.modernizr.com

www.yepnopejs.com www.yepnopejs.com

I thought this will help you. 我认为这会对你有所帮助。

if (typeof scriptname== "undefined") {
   var e = document.createElement("script");
   e.src = "scriptname.js";
   e.type = "text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM