Last active
October 1, 2015 13:47
-
-
Save devfred/2002263 to your computer and use it in GitHub Desktop.
javascript: Load javascript resources asynchronously. Accepts additional parameters that can be passed to the specified callback function
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
/** | |
* Load javascript resources asynchronously. Accepts additional parameters that can be passed to the specified callback function | |
* Author: Frederick King | |
* Date: 3/8/2012 | |
* References/Credits : http://css-tricks.com/thinking-async/ , http://mathiasbynens.be/notes/async-analytics-snippet | |
* | |
**/ | |
var async_load_js = function( url, callback ){ | |
var js, args, rs, s; | |
/* Build script element */ | |
js = document.createElement('script'); | |
/* In IE6 there is a use case where this could fail. If you care about IE6 support you'll probably want to use location.protocol */ | |
js.src = '//' + url; | |
js.type = 'text/javascript'; | |
js.async = 'true'; | |
/* If there are more than 2 args pass the additional args to the callback function as parameters */ | |
args = arguments.length > 2 ? Array.prototype.slice.call( arguments, 2 ) : []; | |
/* Handle callback function */ | |
js.onload = js.onreadystatechange = function(){ | |
rs = this.readyState; | |
if (rs && rs != 'complete' && rs != 'loaded') return; | |
try { callback.apply(this, args) } catch (e) { console.log(e); } | |
}; | |
/* Finally append the script */ | |
s = document.getElementsByTagName('script')[0]; | |
s.parentNode.insertBefore(js, s); | |
}; | |
/* Example Usage */ | |
async_load_js('ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', function(){ | |
console.log("script loaded", arguments); | |
}, 'cbparam1','cbparam2'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment