12

I would like to know how to load an external Javascript into my document from a function.

BenMorel
37.1k53 gold badges208 silver badges339 bronze badges
asked Sep 3, 2009 at 20:19

2 Answers 2

19

This is one way:

function loadDaFun() {
 var script = document.createElement('script');
 script.src = '/path/to/your/script.js';
 var head = document.getElementsByTagName("head")[0];
 head.appendChild(script);
}
Chuck Le Butt
49k62 gold badges213 silver badges299 bronze badges
answered Sep 3, 2009 at 20:23
Sign up to request clarification or add additional context in comments.

1 Comment

type's not necessary, makes no difference (by the way)
13

The @seth's answer is completely right, but you don't need to leave the inserted script element on the DOM, you can remove it just after it is loaded, and also you might want to know when the inserted script is ready to use, for example you can:

function loadScript(url, completeCallback) {
 var script = document.createElement('script'), done = false,
 head = document.getElementsByTagName("head")[0];
 script.src = url;
 script.onload = script.onreadystatechange = function(){
 if ( !done && (!this.readyState ||
 this.readyState == "loaded" || this.readyState == "complete") ) {
 done = true;
 completeCallback();
 // IE memory leak
 script.onload = script.onreadystatechange = null;
 head.removeChild( script );
 }
 };
 head.appendChild(script);
}

Usage:

loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
 function () { alert('jQuery has been loaded.'); });
answered Sep 3, 2009 at 21:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.