Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto include javascript file if not already included

I have an external javascript file that relies on the presence of another file.

How can I, using JavaScript (or jQuery) automatically include this file if it is not already included (I can test based on the presence of a known function in this external file)

Edit: It now includes the file but writes over everything completey! I have tried all suggested methods put forward so far

like image 783
Chris Avatar asked May 21 '10 09:05

Chris


1 Answers

Well if that JavaScript file defines a specific variable (or a function) you can check its presence by checking typeof that_variable, then load the JavaScript file if necessary. An example, here is how you load swfobject library if its not available on the page:

if (typeof swfobject == "undefined") {
   var e = document.createElement("script");
   e.src = "http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js";
   e.type = "text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e); 
}
like image 101
Salman A Avatar answered Sep 21 '22 07:09

Salman A