yes, Ajax is a way to do this, as in the accepted answer. If you go into the details, there are many pitfalls. If you use jQuery.load(...) , the wrong content type is assumed (html instead of application / javascript), which can ruin things by putting unwanted <br> in your (scriptNode) .innerText and the like. Then, if you use jQuery.getScript(...) , the loadable script is executed immediately, which may not be what you want (it may ruin the order in which you want to load the files if you have several of them.)
I found it better to use jQuery.ajax with dataType: "text"
I used this Ajax technique in a frameset project, where a set of frames and / or multiple frames needs the same JavaScript to avoid the server re-sending this JavaScript several times.
Here is the code, tested and works:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html> <head> <script id="scriptData"> var scriptData = [ { name: "foo" , url: "path/to/foo" }, { name: "bar" , url: "path/to/bar" } ]; </script> <script id="scriptLoader"> var LOADER = { loadedCount: 0, toBeLoadedCount: 0, load_jQuery: function (){ var jqNode = document.createElement("script"); jqNode.setAttribute("src", "/path/to/jquery"); jqNode.setAttribute("onload", "LOADER.loadScripts();"); jqNode.setAttribute("id", "jquery"); document.head.appendChild(jqNode); }, loadScripts: function (){ var scriptDataLookup = this.scriptDataLookup = {}; var scriptNodes = this.scriptNodes = {}; var scriptNodesArr = this.scriptNodesArr = []; for (var j=0; j<scriptData.length; j++){ var theEntry = scriptData[j]; scriptDataLookup[theEntry.name] = theEntry; } </script> </head> <frameset rows="200pixels,*" onload="LOADER.load_jQuery();"> <frame src="about:blank"></frame> <frame src="about:blank"></frame> </frameset> </html>
related question
mathheadinclouds Feb 27 '17 at 2:04 on 2017-02-27 14:04
source share