I have a code for defer loading of javascript I am wondering if the code will load the scripts in order (JQuery.min
first) according to where they are in the code ?
function downloadJSAtOnload() {
var element01 = document.createElement("script");
element01.src = "js/jquery.min.js";
document.body.appendChild(element01);
var element02 = document.createElement("script");
element02.src = "js/plugins.js";
document.body.appendChild(element02);
var element03 = document.createElement("script");
element03.src = "js/scripts.js";
document.body.appendChild(element03);
var element04 = document.createElement("script");
element04.src = "js/SmoothScroll.min.js";
document.body.appendChild(element04);
var element05 = document.createElement("script");
element05.src = "js/contact-form.js";
document.body.appendChild(element05);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
If this doesn't load JQuery.min
first and then the other js files how can you make JQuery.min the first script to load and then the rest after that has loaded?
Also I am guessing for example the contact-form.js
will be one of the first to finish loading as it's small so this could cause the Uncaught ReferenceError: $ is not defined
I'm guessing because the JQuery.min hasn't finished downloading so how would you solved this ? I'm guessing an listener / if finished loading load the others else wait...
Thanks in advance