I have the issue of loading the same scripts across all my pages without having to define them all over and over.
I’ve came up with a half complete solution which looks like…
var scriptLocs = [];
function loadScripts() {
for (var i = 0; i < scriptLocs.length; i++) {
var crtElement = document.createElement('script');
crtElement.src = scriptLocs[i];
var hh = document.getElementsByTagName('head')[0];
// Getting head tag
hh.appendChild(crtElement);
//Adding it to head
}
}
The array can be very big e.g. around 120 scripts (2.5MB) these include such things as jQuery and Knockout etc…
The problem im having is this can be unreliable my function seems to miss out, or load in a different order than defined in my array. The order is very important as some things may rely on jQuery so it must be loaded before other scripts.
Also its differnt errors on every refresh … E.g. maybe differnt loading order?
Is there away of define all the scripts in an element then appending the lot of them at once? would this work?
UPDATE:
Using this test.js file
for (var i = 0; i < scriptLocs.length; i++) {
document.write("<script type=\"text/javascript\" src=\"" + scriptLocs[i] + "\"><\/script>");
}
And including it as the very first thing in the head like..
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="test.js"></script>
Seems to solve this problem
This is what
document.write()is for. Frequently it is misused, but in this case, it’s a good choice:But do not put this in a function or call it from an event handler. This script should run immediately while the page is loading. Calling
document.write()after the dom has loaded causes problems.