Import JavaScript file into JavaScript function

Possible duplicates: Include a JavaScript file in a JavaScript file How do I add a JavaScript file to another JavaScript file?

What is the best way to import a JavaScript file, such as file.js , into a JavaScript () function?

For example, what is the best way to replace the todo statement:

 function doSomething() { if (xy.doSomething == undefined) { // TODO: load 'oldVersionPatch.js' } ... } 

Perhaps the best solution is to create a script element and add it to the HTML page.

  • Is it better to add / add it to the head or body (what will load when)?
  • Is it better to use JavaScript or jQuery (which is more compatible with cross-browser)?
+7
source share
4 answers

http://api.jquery.com/jQuery.getScript/

or

 (function(){ this.__defineGetter__("__FILE__", function() { return (new Error).stack.split("\n")[2].split("@")[1].split(":").slice(0,-1).join(":"); }); })(); (function(){ this.__defineGetter__("__DIR__", function() { return __FILE__.substring(0, __FILE__.lastIndexOf('/')); }); })(); function include(file,charset) { if (document.createElement && document.getElementsByTagName) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', __DIR__ + '/' + file); if(charset){ script.setAttribute('charset', charset); } head.appendChild(script); } } 
+4
source
  var filename = 'oldVersionPatch.js'; var js = document.createElement('script'); js.setAttribute("type","text/javascript"); js.setAttribute("src", filename); document.getElementsByTagName("head")[0].appendChild(js); 

.. gotta do it

+4
source

It’s very simple, in JavaScript to create a <script> element, add the src attribute using the URL and attach to the DOM . That should do it.

+1
source

You must make your code asynchronous to get this:

 var script = document.createElement('script'); script.type = 'text/javascript'; script.src = yourJavascriptFileLocation; script.onload = script.onreadystatechange = function() { if (!script.readyState || script.readyState === 'complete') { /* Your code rely on this JavaScript code */ } }; var head = document.getElementsByTagName('head')[0]; // Don't use appendChild head.insertBefore(script, head.firstChild); 
+1
source

All Articles