Created
January 5, 2011 22:16
-
-
Save ryanmcgrath/767131 to your computer and use it in GitHub Desktop.
How to properly branch loading of JS
This file contains 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
/* 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