Dynamically require scripts in the browser, with async callback for when all dependencies are loaded
/* Dynamically require scripts in the browser, with async callback for when all dependencies are loaded | |
Example: | |
function pageReady() { | |
// Init your code here | |
alert('All dependencies loaded!'); | |
} | |
_require(['/json2.js', 'http://server.com/foo.js'], pageReady); | |
The example above insert 2 script tags in the HEAD for /json2.js and http://server.com/foo.js, asynchronously (doesn't block page rendering while the scripts load). | |
The pageReady function will run once all scripts have finished loading so it's safe to start your application. | |
----------------------------------------------------------------------------------*/ | |
var _require = (function () { | |
var handleScriptLoaded; | |
if (document.addEventListener) { | |
handleScriptLoaded = function (elem, callback) { | |
elem.addEventListener('load', callback, false) | |
} | |
} else { | |
handleScriptLoaded = function(elem, callback) { | |
elem.attachEvent('onreadystatechange', function () { | |
if(elem.readyState == 'loaded' || elem.readyState == 'complete') callback() | |
}) | |
} | |
} | |
return function (deps, callback) { | |
var dep_count = 0, | |
dep_length = deps.length; | |
function checkReady (callback) { | |
dep_count++; | |
if ( dep_length == dep_count ) { | |
// Opera needs the timeout for page initialization weirdness | |
setTimeout(callback, 0); | |
} | |
} | |
function addScript (src, callback) { | |
callback = callback || function(){} | |
var head = document.getElementsByTagName('head')[0]; | |
var script = document.createElement('script'); | |
script.setAttribute('src', src); | |
script.setAttribute("type","text/javascript"); | |
script.setAttribute('async', true); | |
handleScriptLoaded(script, function () { | |
checkReady(callback); | |
}); | |
head.appendChild(script); | |
} | |
for(var i = 0; i < dep_length; i++) { | |
addScript(deps[i], callback); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment