<p>How can you reliably and dynamically load a JavaScript file?  This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.</p>

<p>The client that uses the component isn't required to load all the library script files (and manually insert <code>&lt;script&gt;</code> tags into their web page) that implement this component - just the 'main' component script file.</p>

<p><strong>How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?</strong>  Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file?  Or do they do any dynamic loading of ancillary 'library' scripts?</p>

<p>An addition to this question: <strong>is there a way to handle the event after a dynamically included JavaScript file is loaded?</strong>  Prototype has <code>document.observe</code> for document-wide events. Example:</p>

<pre><code>document.observe("dom:loaded", function() {
  // initially hide all containers for tab content
  $$('div.tabcontent').invoke('hide');
});
</code></pre>

<p><strong>What are the available events for a script element?</strong></p>

[{'answer_id': 21297, 'author': 'Adam', 'author_id': 1341, 'author_profile': 'https://Stackoverflow.com/users/1341', 'pm_score': 3, 'selected': False, 'text': '<p>Here is some example code I\'ve found... does anyone have a better way?</p>\n\n<pre><code>  function include(url)\n  {\n    var s = document.createElement("script");\n    s.setAttribute("type", "text/javascript");\n    s.setAttribute("src", url);\n    var nodes = document.getElementsByTagName("*");\n    var node = nodes[nodes.length -1].parentNode;\n    node.appendChild(s);\n  }\n</code></pre>\n'}, {'answer_id': 21300, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 0, 'selected': False, 'text': '<p>all the major javascript libraries like jscript, prototype, YUI have support for loading script files. For example, in YUI, after loading the core you can do the following to load the calendar control</p>\n\n<pre><code>var loader = new YAHOO.util.YUILoader({\n\n    require: [\'calendar\'], // what components?\n\n    base: \'../../build/\',//where do they live?\n\n    //filter: "DEBUG",  //use debug versions (or apply some\n                        //some other filter?\n\n    //loadOptional: true, //load all optional dependencies?\n\n    //onSuccess is the function that YUI Loader\n    //should call when all components are successfully loaded.\n    onSuccess: function() {\n        //Once the YUI Calendar Control and dependencies are on\n        //the page, we\'ll verify that our target container is \n        //available in the DOM and then instantiate a default\n        //calendar into it:\n        YAHOO.util.Event.onAvailable("calendar_container", function() {\n            var myCal = new YAHOO.widget.Calendar("mycal_id", "calendar_container");\n            myCal.render();\n        })\n     },\n\n    // should a failure occur, the onFailure function will be executed\n    onFailure: function(o) {\n        alert("error: " + YAHOO.lang.dump(o));\n    }\n\n });\n\n// Calculate the dependency and insert the required scripts and css resources\n// into the document\nloader.insert();\n</code></pre>\n'}, {'answer_id': 21311, 'author': 'palehorse', 'author_id': 312, 'author_profile': 'https://Stackoverflow.com/users/312', 'pm_score': 4, 'selected': False, 'text': "<p>I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the <code>head</code> element to get the job done.  I simply created an <code>include</code> function (code below) to handle both script and CSS files.</p>\n<p>This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically.  It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.</p>\n<pre><code>function include( url, type ){\n    // First make sure it hasn't been loaded by something else.\n    if( Array.contains( includedFile, url ) )\n        return;\n     \n    // Determine the MIME type.\n    var jsExpr = new RegExp( &quot;js$&quot;, &quot;i&quot; );\n    var cssExpr = new RegExp( &quot;css$&quot;, &quot;i&quot; );\n    if( type == null )\n        if( jsExpr.test( url ) )\n            type = 'text/javascript';\n        else if( cssExpr.test( url ) )\n            type = 'text/css';\n            \n    // Create the appropriate element.\n    var element = null;\n    switch( type ){\n        case 'text/javascript' :\n            element = document.createElement( 'script' );\n            element.type = type;\n            element.src = url;\n            break;\n        case 'text/css' :\n            element = document.createElement( 'link' );\n            element.rel = 'stylesheet';\n            element.type = type;\n            element.href = url;\n            break;\n    }\n    \n    // Insert it to the &lt;head&gt; and the array to ensure it is not\n    // loaded again.\n    document.getElementsByTagName(&quot;head&quot;)[0].appendChild( element );\n    Array.add( includedFile, url );\n}\n</code></pre>\n"}, {'answer_id': 21320, 'author': 'Joseph Pecoraro', 'author_id': 792, 'author_profile': 'https://Stackoverflow.com/users/792', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>does anyone have a better way?</p>\n</blockquote>\n\n<p>I think just adding the script to the body would be easier then adding it to the last node on the page.  How about this:</p>\n\n<pre><code>function include(url) {\n  var s = document.createElement("script");\n  s.setAttribute("type", "text/javascript");\n  s.setAttribute("src", url);\n  document.body.appendChild(s);\n}\n</code></pre>\n'}, {'answer_id': 21392, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 2, 'selected': False, 'text': "<p>The technique we use at work is to request the javascript file using an AJAX request and then eval() the return.  If you're using the prototype library, they support this functionality in their Ajax.Request call.</p>\n"}, {'answer_id': 24313, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 5, 'selected': False, 'text': '<p>I used a <a href="http://gist.github.com/4102" rel="noreferrer">much less complicated version recently</a> with <a href="http://jquery.com/" rel="noreferrer">jQuery</a>:</p>\n\n<pre><code>&lt;script src="scripts/jquery.js"&gt;&lt;/script&gt;\n&lt;script&gt;\n  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];\n  var $head = $("head");\n  for (var i = 0; i &lt; js.length; i++) {\n    $head.append("&lt;script src=\\"" + js[i] + "\\"&gt;&lt;/scr" + "ipt&gt;");\n  }\n&lt;/script&gt;\n</code></pre>\n\n<p>It worked great in every browser I tested it in: IE6/7, Firefox, Safari, Opera.</p>\n\n<p><strong>Update:</strong> jQuery-less version:</p>\n\n<pre><code>&lt;script&gt;\n  var js = ["scripts/jquery.dimensions.js", "scripts/shadedborder.js", "scripts/jqmodal.js", "scripts/main.js"];\n  for (var i = 0, l = js.length; i &lt; l; i++) {\n    document.getElementsByTagName("head")[0].innerHTML += ("&lt;script src=\\"" + js[i] + "\\"&gt;&lt;/scr" + "ipt&gt;");\n  }\n&lt;/script&gt;\n</code></pre>\n'}, {'answer_id': 28249, 'author': 'Pierre Spring', 'author_id': 1532, 'author_profile': 'https://Stackoverflow.com/users/1532', 'pm_score': 2, 'selected': False, 'text': '<p>i\'ve used yet another solution i found on the net ... this one is under creativecommons and it <strong>checks if the source was included prior to calling the function</strong> ...</p>\n\n<p>you can find the file here: <a href="http://xkr.us/code/javascript/include.js" rel="nofollow noreferrer">include.js</a></p>\n\n<pre><code>/** include - including .js files from JS - bfults@gmail.com - 2005-02-09\n ** Code licensed under Creative Commons Attribution-ShareAlike License \n ** http://creativecommons.org/licenses/by-sa/2.0/\n **/              \nvar hIncludes = null;\nfunction include(sURI)\n{   \n  if (document.getElementsByTagName)\n  {   \n    if (!hIncludes)\n    {\n      hIncludes = {}; \n      var cScripts = document.getElementsByTagName("script");\n      for (var i=0,len=cScripts.length; i &lt; len; i++)\n        if (cScripts[i].src) hIncludes[cScripts[i].src] = true;\n    }\n    if (!hIncludes[sURI])\n    {\n      var oNew = document.createElement("script");\n      oNew.type = "text/javascript";\n      oNew.src = sURI;\n      hIncludes[sURI]=true;\n      document.getElementsByTagName("head")[0].appendChild(oNew);\n    }\n  }   \n} \n</code></pre>\n'}, {'answer_id': 242607, 'author': 'aemkei', 'author_id': 28150, 'author_profile': 'https://Stackoverflow.com/users/28150', 'pm_score': 7, 'selected': True, 'text': '<p>You may create a script element dynamically, using <a href="http://www.prototypejs.org/" rel="nofollow noreferrer">Prototypes</a>:</p>\n<pre><code>new Element(&quot;script&quot;, {src: &quot;myBigCodeLibrary.js&quot;, type: &quot;text/javascript&quot;});\n</code></pre>\n<p>The problem here is that we do not know <em>when</em> the external script file is fully loaded.</p>\n<p>We often want our dependant code on the very next line and like to write something like:</p>\n<pre><code>if (iNeedSomeMore) {\n    Script.load(&quot;myBigCodeLibrary.js&quot;); // includes code for myFancyMethod();\n    myFancyMethod(); // cool, no need for callbacks!\n}\n</code></pre>\n<p>There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a <em>synchronous AJAX request</em> and eval the script on global level.</p>\n<p>If you use Prototype the Script.load method looks like this:</p>\n<pre><code>var Script = {\n    _loadedScripts: [],\n    include: function(script) {\n        // include script only once\n        if (this._loadedScripts.include(script)) {\n            return false;\n        }\n        // request file synchronous\n        var code = new Ajax.Request(script, {\n            asynchronous: false,\n            method: &quot;GET&quot;,\n            evalJS: false,\n            evalJSON: false\n        }).transport.responseText;\n        // eval code on global level\n        if (Prototype.Browser.IE) {\n            window.execScript(code);\n        } else if (Prototype.Browser.WebKit) {\n            $$(&quot;head&quot;).first().insert(Object.extend(\n                new Element(&quot;script&quot;, {\n                    type: &quot;text/javascript&quot;\n                }), {\n                    text: code\n                }\n            ));\n        } else {\n            window.eval(code);\n        }\n        // remember included script\n        this._loadedScripts.push(script);\n    }\n};\n</code></pre>\n'}, {'answer_id': 684047, 'author': 'Kariem', 'author_id': 12039, 'author_profile': 'https://Stackoverflow.com/users/12039', 'pm_score': 2, 'selected': False, 'text': '<p>Just found out about a great feature in <a href="http://developer.yahoo.com/yui/3/" rel="nofollow noreferrer">YUI 3</a> (at the time of writing available in preview release). You can easily insert dependencies to YUI libraries and to "external" modules (what you are looking for) without too much code: <a href="http://developer.yahoo.com/yui/3/examples/yui/yui-loader-ext.html" rel="nofollow noreferrer">YUI Loader</a>.</p>\n\n<p>It also answers your second question regarding the function being called as soon as the external module is loaded.</p>\n\n<p>Example:</p>\n\n<pre><code>YUI({\n    modules: {\n        \'simple\': {\n            fullpath: "http://example.com/public/js/simple.js"\n        },\n        \'complicated\': {\n            fullpath: "http://example.com/public/js/complicated.js"\n            requires: [\'simple\']  // &lt;-- dependency to \'simple\' module\n        }\n    },\n    timeout: 10000\n}).use(\'complicated\', function(Y, result) {\n    // called as soon as \'complicated\' is loaded\n    if (!result.success) {\n        // loading failed, or timeout\n        handleError(result.msg);\n    } else {\n        // call a function that needs \'complicated\'\n        doSomethingComplicated(...);\n    }\n});\n</code></pre>\n\n<p>Worked perfectly for me and has the advantage of managing dependencies. Refer to the YUI documentation for an <a href="http://developer.yahoo.com/yui/3/examples/yui/yui-loader-ext_clean.html" rel="nofollow noreferrer">example with YUI 2 calendar</a>.</p>\n'}, {'answer_id': 4689568, 'author': 'JM Design', 'author_id': 572322, 'author_profile': 'https://Stackoverflow.com/users/572322', 'pm_score': 2, 'selected': False, 'text': '<p><strong>jquery resolved this for me with its .append() function</strong>\n- used this to load the complete jquery ui package</p>\n\n<pre><code>/*\n * FILENAME : project.library.js\n * USAGE    : loads any javascript library\n */\n    var dirPath = "../js/";\n    var library = ["functions.js","swfobject.js","jquery.jeditable.mini.js","jquery-ui-1.8.8.custom.min.js","ui/jquery.ui.core.min.js","ui/jquery.ui.widget.min.js","ui/jquery.ui.position.min.js","ui/jquery.ui.button.min.js","ui/jquery.ui.mouse.min.js","ui/jquery.ui.dialog.min.js","ui/jquery.effects.core.min.js","ui/jquery.effects.blind.min.js","ui/jquery.effects.fade.min.js","ui/jquery.effects.slide.min.js","ui/jquery.effects.transfer.min.js"];\n\n    for(var script in library){\n        $(\'head\').append(\'&lt;script type="text/javascript" src="\' + dirPath + library[script] + \'"&gt;&lt;/script&gt;\');\n    }\n</code></pre>\n\n<p><strong>To Use</strong> - in the head of your html/php/etc after you import jquery.js you would just include this one file like so to load in the entirety of your library appending it to the head...</p>\n\n<pre><code>&lt;script type="text/javascript" src="project.library.js"&gt;&lt;/script&gt;\n</code></pre>\n'}, {'answer_id': 9267437, 'author': 'Muhd', 'author_id': 446921, 'author_profile': 'https://Stackoverflow.com/users/446921', 'pm_score': 3, 'selected': False, 'text': '<p>If you have jQuery loaded already, you should use <a href="http://api.jquery.com/jQuery.getScript/">$.getScript</a>.  </p>\n\n<p>This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching.</p>\n'}, {'answer_id': 9268711, 'author': '1nfiniti', 'author_id': 1133102, 'author_profile': 'https://Stackoverflow.com/users/1133102', 'pm_score': 1, 'selected': False, 'text': '<p>There are scripts that are designed specifically for this purpose.</p>\n\n<p><a href="http://yepnopejs.com/" rel="nofollow">yepnope.js</a> is built into Modernizr, and <a href="http://labjs.com/" rel="nofollow">lab.js</a> is a more optimized (but less user friendly version.  </p>\n\n<p>I wouldn\'t reccomend doing this through a big library like jquery or prototype - because one of the major benefits of a script loader is the ability to load scripts early - you shouldn\'t have to wait until jquery &amp; all your dom elements load before running a check to see if you want to dynamically load a script.</p>\n'}, {'answer_id': 10013923, 'author': 'Naveed', 'author_id': 671046, 'author_profile': 'https://Stackoverflow.com/users/671046', 'pm_score': 4, 'selected': False, 'text': '<p>another awesome answer </p>\n\n<pre><code>$.getScript("my_lovely_script.js", function(){\n\n\n   alert("Script loaded and executed.");\n  // here you can use anything you defined in the loaded script\n\n });\n</code></pre>\n\n<p><a href="https://stackoverflow.com/a/950146/671046">https://stackoverflow.com/a/950146/671046</a></p>\n'}, {'answer_id': 14786759, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': "<p>There is no import / include / require in javascript, but there are two main ways to achieve what you want:</p>\n<p>1 - You can load it with an AJAX call then use eval.</p>\n<p>This is the most straightforward way but it's limited to your domain because of the Javascript safety settings, and using eval is opening the door to bugs and hacks.</p>\n<p>2 - Add a script element with the script URL in the HTML.</p>\n<p>Definitely the best way to go. You can load the script even from a foreign server, and it's clean as you use the browser parser to evaluate the code. You can put the <code>script</code> element in the <code>head</code> element of the web page, or at the bottom of the <code>body</code>.</p>\n<p>Both of these solutions are discussed and illustrated here.</p>\n<p>Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performances.</p>\n<p>It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.</p>\n<p>E.G : my_lovely_script.js contains MySuperObject</p>\n<pre><code>var js = document.createElement(&quot;script&quot;);\n\njs.type = &quot;text/javascript&quot;;\njs.src = jsFilePath;\n\ndocument.body.appendChild(js);\n\nvar s = new MySuperObject();\n\nError : MySuperObject is undefined\n</code></pre>\n<p>Then you reload the page hitting F5. And it works! Confusing...</p>\n<p>So what to do about it ?</p>\n<p>Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. E.G :</p>\n<pre><code>function loadScript(url, callback)\n{\n    // adding the script element to the head as suggested before\n   var head = document.getElementsByTagName('head')[0];\n   var script = document.createElement('script');\n   script.type = 'text/javascript';\n   script.src = url;\n\n   // then bind the event to the callback function \n   // there are several events for cross browser compatibility\n   script.onreadystatechange = callback;\n   script.onload = callback;\n\n   // fire the loading\n   head.appendChild(script);\n}\n</code></pre>\n<p>Then you write the code you want to use AFTER the script is loaded in a lambda function :</p>\n<pre><code>var myPrettyCode = function() {\n    // here, do what ever you want\n};\n</code></pre>\n<p>Then you run all that :</p>\n<pre><code>loadScript(&quot;my_lovely_script.js&quot;, myPrettyCode);\n</code></pre>\n<p>Ok, I got it. But it's a pain to write all this stuff.</p>\n<p>Well, in that case, you can use as always the fantastic free jQuery framework, which let you do the very same thing in one line :</p>\n<pre><code>$.getScript(&quot;my_lovely_script.js&quot;, function() {\n    alert(&quot;Script loaded and executed.&quot;);\n    // here you can use anything you defined in the loaded script\n});\n</code></pre>\n"}, {'answer_id': 15976901, 'author': 'stamat', 'author_id': 1909864, 'author_profile': 'https://Stackoverflow.com/users/1909864', 'pm_score': 1, 'selected': False, 'text': '<p>I wrote a simple module that automatizes the job of importing/including module scripts in JavaScript. Give it a try and please spare some feedback! :) For detailed explanation of the code refer to this blog post: <a href="http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/" rel="nofollow">http://stamat.wordpress.com/2013/04/12/javascript-require-import-include-modules/</a></p>\n\n<pre><code>var _rmod = _rmod || {}; //require module namespace\n_rmod.on_ready_fn_stack = [];\n_rmod.libpath = \'\';\n_rmod.imported = {};\n_rmod.loading = {\n    scripts: {},\n    length: 0\n};\n\n_rmod.findScriptPath = function(script_name) {\n    var script_elems = document.getElementsByTagName(\'script\');\n    for (var i = 0; i &lt; script_elems.length; i++) {\n        if (script_elems[i].src.endsWith(script_name)) {\n            var href = window.location.href;\n            href = href.substring(0, href.lastIndexOf(\'/\'));\n            var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);\n            return url.substring(href.length+1, url.length);\n        }\n    }\n    return \'\';\n};\n\n_rmod.libpath = _rmod.findScriptPath(\'script.js\'); //Path of your main script used to mark the root directory of your library, any library\n\n\n_rmod.injectScript = function(script_name, uri, callback, prepare) {\n\n    if(!prepare)\n        prepare(script_name, uri);\n\n    var script_elem = document.createElement(\'script\');\n    script_elem.type = \'text/javascript\';\n    script_elem.title = script_name;\n    script_elem.src = uri;\n    script_elem.async = true;\n    script_elem.defer = false;\n\n    if(!callback)\n        script_elem.onload = function() {\n            callback(script_name, uri);\n        };\n\n    document.getElementsByTagName(\'head\')[0].appendChild(script_elem);\n};\n\n_rmod.requirePrepare = function(script_name, uri) {\n    _rmod.loading.scripts[script_name] = uri;\n    _rmod.loading.length++;\n};\n\n_rmod.requireCallback = function(script_name, uri) {\n    _rmod.loading.length--;\n    delete _rmod.loading.scripts[script_name];\n    _rmod.imported[script_name] = uri;\n\n    if(_rmod.loading.length == 0)\n        _rmod.onReady();\n};\n\n_rmod.onReady = function() {\n    if (!_rmod.LOADED) {\n        for (var i = 0; i &lt; _rmod.on_ready_fn_stack.length; i++){\n            _rmod.on_ready_fn_stack[i]();\n        });\n        _rmod.LOADED = true;\n    }\n};\n\n//you can rename based on your liking. I chose require, but it can be called include or anything else that is easy for you to remember or write, except import because it is reserved for future use.\nvar require = function(script_name) {\n    var np = script_name.split(\'.\');\n    if (np[np.length-1] === \'*\') {\n        np.pop();\n        np.push(\'_all\');\n    }\n\n    script_name = np.join(\'.\');\n    var uri = _rmod.libpath + np.join(\'/\')+\'.js\';\n    if (!_rmod.loading.scripts.hasOwnProperty(script_name) \n     &amp;&amp; !_rmod.imported.hasOwnProperty(script_name)) {\n        _rmod.injectScript(script_name, uri, \n            _rmod.requireCallback, \n                _rmod.requirePrepare);\n    }\n};\n\nvar ready = function(fn) {\n    _rmod.on_ready_fn_stack.push(fn);\n};\n\n// ----- USAGE -----\n\nrequire(\'ivar.util.array\');\nrequire(\'ivar.util.string\');\nrequire(\'ivar.net.*\');\n\nready(function(){\n    //do something when required scripts are loaded\n});\n</code></pre>\n'}, {'answer_id': 16955574, 'author': 'Sielu', 'author_id': 1250626, 'author_profile': 'https://Stackoverflow.com/users/1250626', 'pm_score': 2, 'selected': False, 'text': "<p>If you want a <strong>SYNC</strong> script loading, you need to add script text directly to HTML HEAD element. Adding it as  will trigger an <strong>ASYNC</strong> load. To load script text from external file synchronously, use XHR. Below a quick sample (it is using parts of other answers in this and other posts):</p>\n<pre><code>/*sample requires an additional method for array prototype:*/\n\nif (Array.prototype.contains === undefined) {\nArray.prototype.contains = function (obj) {\n    var i = this.length;\n    while (i--) { if (this[i] === obj) return true; }\n    return false;\n};\n};\n\n/*define object that will wrap our logic*/\nvar ScriptLoader = {\nLoadedFiles: [],\n\nLoadFile: function (url) {\n    var self = this;\n    if (this.LoadedFiles.contains(url)) return;\n\n    var xhr = new XMLHttpRequest();\n    xhr.onload = function () {\n        if (xhr.readyState === 4) {\n            if (xhr.status === 200) {\n                self.LoadedFiles.push(url);\n                self.AddScript(xhr.responseText);\n            } else {\n                if (console) console.error(xhr.statusText);\n            }\n        }\n    };\n    xhr.open(&quot;GET&quot;, url, false);/*last parameter defines if call is async or not*/\n    xhr.send(null);\n},\n\nAddScript: function (code) {\n    var oNew = document.createElement(&quot;script&quot;);\n    oNew.type = &quot;text/javascript&quot;;\n    oNew.textContent = code;\n    document.getElementsByTagName(&quot;head&quot;)[0].appendChild(oNew);\n}\n};\n\n/*Load script file. ScriptLoader will check if you try to load a file that has already been loaded (this check might be better, but I'm lazy).*/\n\nScriptLoader.LoadFile(&quot;Scripts/jquery-2.0.1.min.js&quot;);\nScriptLoader.LoadFile(&quot;Scripts/jquery-2.0.1.min.js&quot;);\n/*this will be executed right after upper lines. It requires jquery to execute. It requires a HTML input with id &quot;tb1&quot;*/\n$(function () { alert($('#tb1').val()); });\n</code></pre>\n"}, {'answer_id': 28389499, 'author': 'tfont', 'author_id': 1804013, 'author_profile': 'https://Stackoverflow.com/users/1804013', 'pm_score': 2, 'selected': False, 'text': '<p>Keep it nice, short, simple, and maintainable! :]</p>\n\n<pre><code>// 3rd party plugins / script (don\'t forget the full path is necessary)\nvar FULL_PATH = \'\', s =\n[\n    FULL_PATH + \'plugins/script.js\'      // Script example\n    FULL_PATH + \'plugins/jquery.1.2.js\', // jQuery Library \n    FULL_PATH + \'plugins/crypto-js/hmac-sha1.js\',      // CryptoJS\n    FULL_PATH + \'plugins/crypto-js/enc-base64-min.js\'  // CryptoJS\n];\n\nfunction load(url)\n{\n    var ajax = new XMLHttpRequest();\n    ajax.open(\'GET\', url, false);\n    ajax.onreadystatechange = function ()\n    {\n        var script = ajax.response || ajax.responseText;\n        if (ajax.readyState === 4)\n        {\n            switch(ajax.status)\n            {\n                case 200:\n                    eval.apply( window, [script] );\n                    console.log("library loaded: ", url);\n                    break;\n                default:\n                    console.log("ERROR: library not loaded: ", url);\n            }\n        }\n    };\n    ajax.send(null);\n}\n\n // initialize a single load \nload(\'plugins/script.js\');\n\n// initialize a full load of scripts\nif (s.length &gt; 0)\n{\n    for (i = 0; i &lt; s.length; i++)\n    {\n        load(s[i]);\n    }\n}\n</code></pre>\n\n<p>This code is simply a short functional example that <em>could</em> require additional feature functionality for full support on any (or given) platform.</p>\n'}, {'answer_id': 35793206, 'author': 'adrianTNT', 'author_id': 928532, 'author_profile': 'https://Stackoverflow.com/users/928532', 'pm_score': 1, 'selected': False, 'text': '<p>I am lost in all these samples but today I needed to load an external .js from my main .js and I did this:</p>\n\n<pre><code>document.write("&lt;script src=\'https://www.google.com/recaptcha/api.js\'&gt;&lt;/script&gt;");\n</code></pre>\n'}, {'answer_id': 42667747, 'author': 'Jacob', 'author_id': 665783, 'author_profile': 'https://Stackoverflow.com/users/665783', 'pm_score': 1, 'selected': False, 'text': '<p><a href="https://www.sitepoint.com/dynamically-load-jquery-library-javascript/" rel="nofollow noreferrer">Here</a> is a simple one with callback and IE support:</p>\n\n<pre><code>function loadScript(url, callback) {\n\n    var script = document.createElement("script")\n    script.type = "text/javascript";\n\n    if (script.readyState) { //IE\n        script.onreadystatechange = function () {\n            if (script.readyState == "loaded" || script.readyState == "complete") {\n                script.onreadystatechange = null;\n                callback();\n            }\n        };\n    } else { //Others\n        script.onload = function () {\n            callback();\n        };\n    }\n\n    script.src = url;\n    document.getElementsByTagName("head")[0].appendChild(script);\n}\n\nloadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {\n\n     //jQuery loaded\n     console.log(\'jquery loaded\');\n\n});\n</code></pre>\n'}, {'answer_id': 45488894, 'author': 'asmmahmud', 'author_id': 1576255, 'author_profile': 'https://Stackoverflow.com/users/1576255', 'pm_score': 2, 'selected': False, 'text': '<p>I know my answer is bit late for this question, but, here is a great article in <strong>www.html5rocks.com</strong> - <a href="https://www.html5rocks.com/en/tutorials/speed/script-loading/#toc-aggressive-optimisation" rel="nofollow noreferrer">Deep dive into the murky waters of script loading</a> .</p>\n\n<p>In that article it is concluded that in regards of browser support, the best way to dynamically load JavaScript file without blocking content rendering is the following way:  </p>\n\n<p>Considering you\'ve four scripts named <code>script1.js, script2.js, script3.js, script4.js</code> then you can do it with <strong>applying async = false</strong>: </p>\n\n<pre><code>[\n  \'script1.js\',\n  \'script2.js\',\n  \'script3.js\',\n  \'script4.js\'\n].forEach(function(src) {\n  var script = document.createElement(\'script\');\n  script.src = src;\n  script.async = false;\n  document.head.appendChild(script);\n});\n</code></pre>\n\n<p>Now, <strong>Spec says</strong>: Download together, execute in order as soon as all download.</p>\n\n<p><strong>Firefox &lt; 3.6, Opera says:</strong> I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.</p>\n\n<p><strong>Safari 5.0 says:</strong> I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.</p>\n\n<p><strong>IE &lt; 10 says:</strong> No idea about “async”, but there is a workaround using “onreadystatechange”.</p>\n\n<p><strong>Everything else says:</strong> I’m your friend, we’re going to do this by the book.</p>\n\n<p><strong>Now, the full code with IE &lt; 10 workaround:</strong> </p>\n\n<pre><code>var scripts = [\n  \'script1.js\',\n  \'script2.js\',\n  \'script3.js\',\n  \'script4.js\'\n];\nvar src;\nvar script;\nvar pendingScripts = [];\nvar firstScript = document.scripts[0];\n\n// Watch scripts load in IE\nfunction stateChange() {\n  // Execute as many scripts in order as we can\n  var pendingScript;\n  while (pendingScripts[0] &amp;&amp; pendingScripts[0].readyState == \'loaded\') {\n    pendingScript = pendingScripts.shift();\n    // avoid future loading events from this script (eg, if src changes)\n    pendingScript.onreadystatechange = null;\n    // can\'t just appendChild, old IE bug if element isn\'t closed\n    firstScript.parentNode.insertBefore(pendingScript, firstScript);\n  }\n}\n\n// loop through our script urls\nwhile (src = scripts.shift()) {\n  if (\'async\' in firstScript) { // modern browsers\n    script = document.createElement(\'script\');\n    script.async = false;\n    script.src = src;\n    document.head.appendChild(script);\n  }\n  else if (firstScript.readyState) { // IE&lt;10\n    // create a script and add it to our todo pile\n    script = document.createElement(\'script\');\n    pendingScripts.push(script);\n    // listen for state changes\n    script.onreadystatechange = stateChange;\n    // must set src AFTER adding onreadystatechange listener\n    // else we’ll miss the loaded event for cached scripts\n    script.src = src;\n  }\n  else { // fall back to defer\n    document.write(\'&lt;script src="\' + src + \'" defer&gt;&lt;/\'+\'script&gt;\');\n  }\n}\n</code></pre>\n\n<p><strong>A few tricks and minification later, it’s 362 bytes</strong>  </p>\n\n<pre><code>!function(e,t,r){function n(){for(;d[0]&amp;&amp;"loaded"==d[0][f];)c=d.shift(),c[o]=!i.parentNode.insertBefore(c,i)}for(var s,a,c,d=[],i=e.scripts[0],o="onreadystatechange",f="readyState";s=r.shift();)a=e.createElement(t),"async"in i?(a.async=!1,e.head.appendChild(a)):i[f]?(d.push(a),a[o]=n):e.write("&lt;"+t+\' src="\'+s+\'" defer&gt;&lt;/\'+t+"&gt;"),a.src=s}(document,"script",[\n  "//other-domain.com/1.js",\n  "2.js"\n])\n</code></pre>\n'}, {'answer_id': 49889707, 'author': 'James Arnold', 'author_id': 2558016, 'author_profile': 'https://Stackoverflow.com/users/2558016', 'pm_score': 2, 'selected': False, 'text': '<p>Something like this...</p>\n\n<pre><code>&lt;script&gt;\n     $(document).ready(function() {\n          $(\'body\').append(\'&lt;script src="https://maps.googleapis.com/maps/api/js?key=KEY&amp;libraries=places&amp;callback=getCurrentPickupLocation" async defer&gt;&lt;\\/script&gt;\');\n     });\n&lt;/script&gt;\n</code></pre>\n'}, {'answer_id': 50051689, 'author': 'João Pimentel Ferreira', 'author_id': 1243247, 'author_profile': 'https://Stackoverflow.com/users/1243247', 'pm_score': 1, 'selected': False, 'text': '<p>Here a simple example for a function to load JS files. Relevant points:</p>\n\n<ul>\n<li>you don\'t need jQuery, so you may use this initially to load also the jQuery.js file</li>\n<li>it is async with callback</li>\n<li>it ensures it loads only once, as it keeps an enclosure with the record of loaded urls, thus avoiding usage of network</li>\n<li>contrary to jQuery <code>$.ajax</code> or <code>$.getScript</code> you can use nonces, solving thus issues with CSP <code>unsafe-inline</code>. Just use the property <code>script.nonce</code></li>\n</ul>\n\n<pre class="lang-js prettyprint-override"><code>var getScriptOnce = function() {\n\n    var scriptArray = []; //array of urls (closure)\n\n    //function to defer loading of script\n    return function (url, callback){\n        //the array doesn\'t have such url\n        if (scriptArray.indexOf(url) === -1){\n\n            var script=document.createElement(\'script\');\n            script.src=url;\n            var head=document.getElementsByTagName(\'head\')[0],\n                done=false;\n\n            script.onload=script.onreadystatechange = function(){\n                if ( !done &amp;&amp; (!this.readyState || this.readyState == \'loaded\' || this.readyState == \'complete\') ) {\n                    done=true;\n                    if (typeof callback === \'function\') {\n                        callback();\n                    }\n                    script.onload = script.onreadystatechange = null;\n                    head.removeChild(script);\n\n                    scriptArray.push(url);\n                }\n            };\n\n            head.appendChild(script);\n        }\n    };\n}();\n</code></pre>\n\n\n\n<p>Now you use it simply by</p>\n\n<pre><code>getScriptOnce("url_of_your_JS_file.js");\n</code></pre>\n'}, {'answer_id': 51378436, 'author': 'Alister', 'author_id': 1432509, 'author_profile': 'https://Stackoverflow.com/users/1432509', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s a new proposed ECMA standard called <a href="https://developers.google.com/web/updates/2017/11/dynamic-import" rel="nofollow noreferrer">dynamic import</a>, recently incorporated into Chrome and Safari.  </p>\n\n<pre><code>const moduleSpecifier = \'./dir/someModule.js\';\n\nimport(moduleSpecifier)\n   .then(someModule =&gt; someModule.foo()); // executes foo method in someModule\n</code></pre>\n'}, {'answer_id': 52365356, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>An absurd one-liner, for those who think that loading a js library shouldn\'t take more than one line of code :P</p>\n\n<pre><code>await new Promise((resolve, reject) =&gt; {let js = document.createElement("script"); js.src="mylibrary.js"; js.onload=resolve; js.onerror=reject; document.body.appendChild(js)});\n</code></pre>\n\n<p>Obviously if the script you want to import is a module, you can use the <a href="https://developers.google.com/web/updates/2017/11/dynamic-import" rel="nofollow noreferrer"><code>import(...)</code></a> function.</p>\n'}, {'answer_id': 57367916, 'author': 'NVRM', 'author_id': 2494754, 'author_profile': 'https://Stackoverflow.com/users/2494754', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports" rel="nofollow noreferrer">Dynamic <strong>module</strong> import landed in Firefox 67+</a>.</p>\n<pre><code>(async () =&gt; {\n   await import(\'./synth/BubbleSynth.js\')\n})()\n</code></pre>\n<p>With error handling:</p>\n<pre><code>(async () =&gt; {\n    await import(\'./synth/BubbleSynth.js\').catch((error) =&gt; console.log(\'Loading failed\' + error))\n})()\n</code></pre>\n<hr />\n<p>It also works for any kind of non-modules libraries, on this case the lib is available on the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/self" rel="nofollow noreferrer"><code>window.self</code></a> object, the old way, but only on demand, which is nice.</p>\n<p>Example using <a href="https://github.com/mourner/suncalc" rel="nofollow noreferrer">suncalc.js</a>, the server must have <strong><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" rel="nofollow noreferrer">CORS enabled</a></strong> to works this way!</p>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>(async () =&gt; {\n await import(\'https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.8.0/suncalc.min.js\')\n .then( () =&gt; {\n   let times = SunCalc.getTimes(new Date(), 51.5,-0.1);\n   console.log("Golden Hour today in London: " + times.goldenHour.getHours() + \':\' + times.goldenHour.getMinutes() + ". Take your pics!")\n  })\n})()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href="https://caniuse.com/#feat=es6-module-dynamic-import" rel="nofollow noreferrer">https://caniuse.com/#feat=es6-module-dynamic-import</a></p>\n'}, {'answer_id': 59012155, 'author': 'VG P', 'author_id': 3936513, 'author_profile': 'https://Stackoverflow.com/users/3936513', 'pm_score': 0, 'selected': False, 'text': '<p>I have tweaked some of the above post with working example.\nHere we can give css and js in same array also.</p>\n\n<pre><code>$(document).ready(function(){\n\nif (Array.prototype.contains === undefined) {\nArray.prototype.contains = function (obj) {\n    var i = this.length;\n    while (i--) { if (this[i] === obj) return true; }\n    return false;\n};\n};\n\n/* define object that will wrap our logic */\nvar jsScriptCssLoader = {\n\njsExpr : new RegExp( "js$", "i" ),\ncssExpr : new RegExp( "css$", "i" ),\nloadedFiles: [],\n\nloadFile: function (cssJsFileArray) {\n    var self = this;\n    // remove duplicates with in array\n    cssJsFileArray.filter((item,index)=&gt;cssJsFileArray.indexOf(item)==index)\n    var loadedFileArray = this.loadedFiles;\n    $.each(cssJsFileArray, function( index, url ) {\n            // if multiple arrays are loaded the check the uniqueness\n            if (loadedFileArray.contains(url)) return;\n            if( self.jsExpr.test( url ) ){\n                $.get(url, function(data) {\n                    self.addScript(data);\n                });\n\n            }else if( self.cssExpr.test( url ) ){\n                $.get(url, function(data) {\n                    self.addCss(data);\n                });\n            }\n\n            self.loadedFiles.push(url);\n    });\n\n    // don\'t load twice accross different arrays\n\n},\naddScript: function (code) {\n    var oNew = document.createElement("script");\n    oNew.type = "text/javascript";\n    oNew.textContent = code;\n    document.getElementsByTagName("head")[0].appendChild(oNew);\n},\naddCss: function (code) {\n    var oNew = document.createElement("style");\n    oNew.textContent = code;\n    document.getElementsByTagName("head")[0].appendChild(oNew);\n}\n\n};\n\n\n//jsScriptCssLoader.loadFile(["css/1.css","css/2.css","css/3.css"]);\njsScriptCssLoader.loadFile(["js/common/1.js","js/2.js","js/common/file/fileReader.js"]);\n});\n</code></pre>\n'}, {'answer_id': 59612206, 'author': 'radulle', 'author_id': 3008018, 'author_profile': 'https://Stackoverflow.com/users/3008018', 'pm_score': 2, 'selected': False, 'text': '<p>With Promises you can simplify it like this.\nLoader function:</p>\n\n<pre><code>  const loadCDN = src =&gt;\n    new Promise((resolve, reject) =&gt; {\n      if (document.querySelector(`head &gt; script[src="${src}"]`) !== null) return resolve()\n      const script = document.createElement("script")\n      script.src = src\n      script.async = true\n      document.head.appendChild(script)\n      script.onload = resolve\n      script.onerror = reject\n    })\n</code></pre>\n\n<p>Usage (async/await):</p>\n\n<pre><code>await loadCDN("https://.../script.js")\n</code></pre>\n\n<p>Usage (Promise):</p>\n\n<pre><code>loadCDN("https://.../script.js").then(res =&gt; {}).catch(err =&gt; {})\n</code></pre>\n\n<p>NOTE: there was one similar solution but it doesn\'t check if the script is already loaded and loads the script each time. This one checks src property.</p>\n'}, {'answer_id': 60248096, 'author': 'Ludmil Tinkov', 'author_id': 519553, 'author_profile': 'https://Stackoverflow.com/users/519553', 'pm_score': 1, 'selected': False, 'text': '<p>For those of you, who love one-liners:</p>\n\n<pre><code>import(\'./myscript.js\');\n</code></pre>\n\n<p>Chances are you might get an error, like:</p>\n\n<blockquote>\n  <p>Access to script at \'<a href="http://..../myscript.js" rel="nofollow noreferrer">http://..../myscript.js</a>\' from origin\n  \'<a href="http://127.0.0.1" rel="nofollow noreferrer">http://127.0.0.1</a>\' has been blocked by CORS policy: No\n  \'Access-Control-Allow-Origin\' header is present on the requested\n  resource.</p>\n</blockquote>\n\n<p>In which case, you can fallback to:</p>\n\n<pre><code>fetch(\'myscript.js\').then(r =&gt; r.text()).then(t =&gt; new Function(t)());\n</code></pre>\n'}, {'answer_id': 67646541, 'author': 'Enrico', 'author_id': 7116948, 'author_profile': 'https://Stackoverflow.com/users/7116948', 'pm_score': 1, 'selected': False, 'text': '<p>In as much as I love how handy the JQuery approach is, the JavaScript approach isn\'t that complicated but just require little tweaking to what you already use...\nHere is how I load JS dynamically(Only when needed), and wait for them to load before executing the script that depends on them.</p>\n<p><strong>JavaScript Approach</strong></p>\n<pre><code>//Create a script element that will load\nlet dynamicScript = document.createElement(\'script\');\n\n//Set source to the script we need to load\ndynamicScript.src = \'linkToNeededJsFile.js\';\n\n//Set onload to callback function that depends on this script or do inline as shown below\ndynamicScript.onload = () =&gt; {\n\n    //Code that depends on the loaded script should be here\n\n};\n\n//append the created script element to body element\ndocument.body.append(dynamicScript);\n</code></pre>\n<p>There are other ways approach one could accomplish this with JS but, I prefer this as it\'s require the basic JS knowledge every dev can relate.</p>\n<p>Not part of the answer but here is the JQuery version I prefer with projects that already include JQuery:</p>\n<pre><code>$.getScript(\'linkToNeededJsFile.js\', () =&gt; {\n\n    //Code that depends on the loaded script should be here\n\n});\n</code></pre>\n<p>More on the JQuery option <a href="https://api.jquery.com/jQuery.getScript/" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 72079575, 'author': 'vatavale', 'author_id': 1056384, 'author_profile': 'https://Stackoverflow.com/users/1056384', 'pm_score': 1, 'selected': False, 'text': '<p>This function uses memorization. And could be called many times with no conflicts of loading and running the same script twice. Also it\'s not resolving sooner than the script is actually loaded (like in <a href="https://stackoverflow.com/a/59612206/1056384">@radulle</a> answer).</p>\n<pre><code>const loadScript = function () {\n    let cache = {};\n    return function (src) {\n        return cache[src] || (cache[src] = new Promise((resolve, reject) =&gt; {\n            let s = document.createElement(\'script\');\n            s.defer = true;\n            s.src = src;\n            s.onload = resolve;\n            s.onerror = reject;\n            document.head.append(s);\n        }));\n    }\n}();\n</code></pre>\n<p>Please notice the parentheses () after the function expression.</p>\n<p>Parallel loading of scripts:</p>\n<pre><code>Promise.all([\n    loadScript(\'/script1.js\'),\n    loadScript(\'/script2.js\'),\n    // ...\n]).then(() =&gt; {\n    // do something\n})\n</code></pre>\n<p>You can use the same method for <a href="https://stackoverflow.com/a/72082566/1056384">dynamic loading stylesheets</a>.</p>\n'}]
['https://Stackoverflow.com/questions/21294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1341/']