Skip to content

Instantly share code, notes, and snippets.

@devfred
Last active October 1, 2015 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devfred/2002263 to your computer and use it in GitHub Desktop.
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
/**
* 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