5

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.

Kuldeep Daftary
  • 611
  • 3
  • 16
  • 31
  • 1
    Given the use case, you could reverse the condition, do away with the `else`, just call the function outside of the `if-else` block after loading the script. –  Sep 17 '12 at 09:44
  • possible duplicate http://stackoverflow.com/questions/11599311/check-whether-all-the-jquery-files-are-loaded-then-run-the-div-related-to-it/11599351#11599351 – Netorica Sep 17 '12 at 09:45
  • @Mahan This is not a possible Duplicate. My requirements are different.. Thanks – Kuldeep Daftary Sep 17 '12 at 09:52

6 Answers6

7

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+"']");
Ben Thielker
  • 4,104
  • 4
  • 21
  • 20
6

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
}
Zathrus Writer
  • 4,311
  • 5
  • 27
  • 50
2

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.

Ranjith Ramachandra
  • 10,399
  • 14
  • 59
  • 96
0

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
nbrooks
  • 18,126
  • 5
  • 54
  • 66
0

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

www.headjs.com

www.modernizr.com

www.yepnopejs.com

Netorica
  • 18,523
  • 17
  • 73
  • 108
0

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); 
}
tom joy
  • 411
  • 8
  • 22