Created
October 15, 2012 14:41
-
-
Save chapmanjw/3892839 to your computer and use it in GitHub Desktop.
Load jQuery and Plugins Async: http://www.sharepointjohn.com/javascript-loading-jquery-jquery-plugins-asynchronously/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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