Skip to content

Instantly share code, notes, and snippets.

@ryanmcgrath
Created January 5, 2011 22:16
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ryanmcgrath/767131 to your computer and use it in GitHub Desktop.
Save ryanmcgrath/767131 to your computer and use it in GitHub Desktop.
How to properly branch loading of JS
/* Since script loading is dynamic, we take
a callback function with our loadScript call
that executes once the script is done downloading/parsing
on the page.
*/
var loadScript = function(src, callbackfn) {
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", src);
if(newScript.readyState) {
newScript.onreadystatechange = function() {
if(/loaded|complete/.test(newScript.readyState)) callbackfn();
}
} else {
newScript.addEventListener("load", callbackfn, false);
}
document.documentElement.firstChild.appendChild(newScript);
}
if(a) {
loadScript("lulz.js", function() { ... });
} else {
loadScript("other_lulz.js", function() { ... });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment