In order to improve the page performance I need to preload scripts that I will need to run on the bottom page.
I
For each script you'd like to download without executing, make an object containing a name and a url, and put those objects into an array.
Looping through the array, use jQuery.ajax
with dataType: "text"
to download your scripts as text. In the done
handler of the ajax call, store the text content of the file (which is passed in first argument) in the appropriate object, increment a counter, and call an "alldone" function when that counter is equal to the number of files you are downloading in this manner.
In the "alldone" function (or later) do the following: Loop through your array again, and for each entry, use document.createElement("script")
, document.createTextNode(...)
, and (...scriptNode...).appendChild(...)
to dynamically generate scripts having the intended source inline, rather than via "src" attribute. Finally, do document.head.appendChild(...scriptNode...)
, which is the point when that script is executed.
I have used this technique in a project where I needed to use frames, where several frames and/or the frameset need identical JavaScript files, in order to make sure each of those files is requested only once from the server.
Code (tested and working) follows
other question closely related to above approach other related question