8

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

2 Answers 2

12

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); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a note... I tried this in jQuery's document ready function and then tried calling the function in my file and it was still undefined. Ended up doing it a different way.
@RegionalC: you must call that function after the dynamically loaded script is loaded. On most browsers, you can assign an onload event to dynamically generated script elements (e.onload = function() {}). You can call your function from within that event handler. On (stupid) IE 6/7/8 you can use onreadystatechange event.
1

http://www.cryer.co.uk/resources/javascript/script17_include_js_from_js.htm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.