Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 921
Kuldeep Daftary Avatar asked Sep 17 '12 09:09

Kuldeep Daftary


3 Answers

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.

With jquery:

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

Without jquery:

document.querySelector("script[src*='"+scriptName+"']");
like image 96
Ben Thielker Avatar answered Nov 20 '22 16:11

Ben Thielker


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
}
like image 6
Zathrus Writer Avatar answered Nov 20 '22 18:11

Zathrus Writer


I agree with @zathrus though I think you should be using requirejs for things like this. 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. It is very easy to learn as well.

like image 2
Ranjith Ramachandra Avatar answered Nov 20 '22 17:11

Ranjith Ramachandra