Last active
September 11, 2017 17:06
-
-
Save dvlden/d668845371139bd748ff to your computer and use it in GitHub Desktop.
Load any Script files - The asynchronous way
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
/* Example of how to load Facebook SDK */ | |
loadAsync(document, 'script', '//connect.facebook.net/en_US/sdk.js', 'facebook-jssdk', successCallback); | |
function successCallback () { | |
console.log('Facebook\'s SDK successfully loaded.'); | |
} | |
/* Asynchronously load any script files */ | |
function loadAsync ( doc, elem, source, id, cb ) { | |
var ready = false, | |
newElem, | |
tag = doc.getElementsByTagName(elem)[0]; | |
if ( doc.getElementById(id) ) return; | |
newElem = doc.createElement(elem); | |
newElem.id = id; | |
newElem.async = 'async'; | |
newElem.src = source; | |
if ( typeof(cb) === "function" ) { | |
newElem.onload = newElem.onreadystatechange = function () { | |
if ( !ready && ( !this.readyState || this.readyState == 'complete' ) ) { | |
ready = true; | |
cb(); | |
} | |
}; | |
} | |
tag.parentNode.insertBefore(newElem, tag); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment