Created
December 6, 2012 15:41
-
-
Save beaspider/4225446 to your computer and use it in GitHub Desktop.
lazy load 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
// can be used for JSONP calls too | |
var loadScript = function(url, callback) { | |
var script = document.createElement('script'); | |
script.setAttribute('src', url); | |
script.setAttribute("type","text/javascript"); | |
script.setAttribute('async', true); | |
// wait for script to load | |
var onLoaded = function(script,callback) { | |
return function() { | |
// remove the script | |
document.getElementsByTagName('head')[0].removeChild(script); | |
// run any callback | |
if (callback) { | |
callback(); | |
} | |
} | |
} | |
if (document.addEventListener) { | |
script.addEventListener('load',onLoaded(script,callback), false); | |
} else { | |
elem.attachEvent('onreadystatechange', function () { | |
if (elem.readyState == 'loaded' || elem.readyState == 'complete') { | |
onLoaded(script,callback)(); | |
} | |
}); | |
} | |
document.getElementsByTagName('head')[0].appendChild(script); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment