Skip to content

Instantly share code, notes, and snippets.

@robsonsobral
Forked from chapmanjw/LoadJS.js
Created April 17, 2018 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robsonsobral/0d720a7591382e2047a3de103c54bdde to your computer and use it in GitHub Desktop.
Save robsonsobral/0d720a7591382e2047a3de103c54bdde to your computer and use it in GitHub Desktop.
/*
This function will take the scripts specified and load them in order
asynchronously. It will not continue until the specified type from
each file is loaded.
*/
(function () {
function loadScripts () {
/*
This loadScript function takes the name of the object as it
will be assigned to its parent. For instance, jQuery is the
name of the object assigned to the window object. For the
plugins, the object name is the name of the jQuery function.
For instance, for a function that runs like $.plugin(), the
function name to specify is 'plugin'.
The loadScript will either look for the new object on the
window object or in the jQuery functions. Specify whether
to look on the 'window' or 'jquery' object. For the most
part, only jQuery will be on the 'window' and everything
else will be 'jquery'
*/
loadScript('jQuery', '/jquery-1.7.2.min.js', 'window');
loadScript('plugin', '/jquery-plugin.js', 'jquery');
}
loadScripts();
function loadScript (objectType, scriptUrl, parentObject) {
var isDef = isDefined (objectType, parentObject);
if (!isDef) {
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = scriptUrl;
scriptElement.async = true;
document.body.appendChild(scriptElement);
loadScriptsWait(objectType, parentObject, function () {
// Write to the console that the JS loaded
console.log(scriptUrl + ' loaded');
});
}
}
function isDefined (objectType, parentObject) {
switch (parentObject) {
case 'window':
if (typeof window[objectType] != 'undefined') {
return true;
}
break;
case 'jquery':
if (typeof jQuery.fn[objectType] != 'undefined') {
return true;
}
break;
}
return false;
}
function loadScriptsWait(objectType, parentObject, callback) {
var isDef = isDefined (objectType, parentObject);
if (!isDef) {
setTimeout(function () {
loadScriptsWait(objectType, parentObject, callback);
}, 200);
} else {
callback && callback();
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment