Check if javascript is attached to the page?

Is there any way to check if the javascript file is attached to the page by file name.

For instance,

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 don't want 1 script to be attached twice on the same page.

+4
source share
6 answers

You may not always know which objects or functions the script contains, in such cases you can look for script tags that contain the required src file.

With jquery:

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

Without jquery:

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

You need to check if the actual function from the script file exists, for example:

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

I agree with @zathrus, although I think you should use requirejs for such things. The idea is that dependencies must be obtained before executing the code. The above method that you use may work, but you cannot guarantee anything.

RequireJS will perfectly support dependency loading. It is also very easy to find out.

+2
source

Just 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 
0
source

you really need a script loader .. because, as you said, you want it to be defined with the javascript resource file name, and that your javascript files are dependent on each other.

www.headjs.com

www.modernizr.com

www.yepnopejs.com

0
source

I thought this would 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); } 
0
source

Source: https://habr.com/ru/post/1434570/


All Articles