Created
December 17, 2019 12:10
-
-
Save raazon/69999423c53d7c6d14ed2f726bfeefbd to your computer and use it in GitHub Desktop.
Load scripts asynchronously
This file contains hidden or 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
// If you user jQuery: https://api.jquery.com/jQuery.getScript/ | |
// $.getScript(url, successCallback) | |
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) { | |
console.log( data ); // Data returned | |
console.log( textStatus ); // Success | |
console.log( jqxhr.status ); // 200 | |
console.log( "Load was performed." ); | |
}); | |
// Handling Errors | |
$.getScript( "ajax/test.js" ) | |
.done(function( script, textStatus ) { | |
console.log( textStatus ); | |
}) | |
.fail(function( jqxhr, settings, exception ) { | |
console.log( "Triggered ajaxError handler." ); | |
}); | |
// For JavaScript | |
// REF: https://stackoverflow.com/questions/7718935/load-scripts-asynchronously/7719185#answer-7719185 | |
function loadScript(src, callback) { | |
var s, | |
r, | |
t; | |
r = false; | |
s = document.createElement('script'); | |
s.type = 'text/javascript'; | |
s.src = src; | |
s.onload = s.onreadystatechange = function () { | |
//console.log( this.readyState ); //uncomment this line to see which ready states are called. | |
if (!r && (!this.readyState || this.readyState == 'complete')) { | |
r = true; | |
callback(); | |
} | |
}; | |
t = document.getElementsByTagName('script')[0]; | |
t.parentNode.insertBefore(s, t); | |
} | |
loadScript(src, callback); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment