For each script that you want to load without execution, create an object containing the name and URL, and put these objects in an array.
Scrolling through an array, use jQuery.ajax with dataType: "text" to load your scripts as text. In the done handler of the ajax call, save the text content of the file (which is passed in the first argument) in the corresponding object, increase the counter and call the "alldone" function when this counter is equal to the number of files that you load in this way.
In the "alldone" (or later) function, do the following: loop through your array and use document.createElement("script") , document.createTextNode(...) and (...scriptNode...).appendChild(...) for each entry (...scriptNode...).appendChild(...) for dynamically creating scripts that have an alleged inline source, and not through the "src" attribute. Finally, do document.head.appendChild(...scriptNode...) , which is the point when the script is executed.
I used this technique in a project where I needed to use frames, where several frames and / or a set of frames needed identical JavaScript files to make sure that each of these files is requested only once from the server.
Code (verified and working) follows
<!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>
another issue closely related to the above approach another related issue
mathheadinclouds Feb 27 '17 at 13:32 2017-02-27 13:32
source share