Skip to content

Instantly share code, notes, and snippets.

@hekt
Created April 4, 2014 13:13
Show Gist options
  • Save hekt/9974458 to your computer and use it in GitHub Desktop.
Save hekt/9974458 to your computer and use it in GitHub Desktop.
JavaScript Loader
function jsLoader() {
"use strict";
var scripts = [].slice.call(arguments);
var reserves = [];
var thisScript = document.scripts[0] || document.querySelector("script");
var head = thisScript.parentNode;
if ("async" in thisScript)
parallel();
else if (thisScript.readyState)
parallelForIE();
else
sequential();
function parallel() {
scripts.forEach(function (script) {
var elem = document.createElement("script");
elem.async = false;
elem.src = script;
head.insertBefore(elem, thisScript);
});
}
function parallelForIE() {
scripts.forEach(function (script) {
var elem = document.createElement("script");
reserves.push(elem);
elem.onreadystatechange = stateChange;
elem.src = script;
});
}
function sequential() {
var script = scripts.shift();
var elem;
if (script) {
elem = document.createElement("script");
elem.src = script;
elem.onload = sequential;
head.insertBefore(elem, thisScript);
}
}
function stateChange() {
var elem;
while (reserves[0] && reserves[0].readyState === "loaded") {
elem = reserves.shift();
elem.onreadystatechange = null;
head.insertBefore(elem, thisScript);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment