Skip to content

Instantly share code, notes, and snippets.

@Shoora
Forked from devfred/async_load.js
Last active February 28, 2019 03:35
Show Gist options
  • Save Shoora/6d4d6a009a2a975b0a40 to your computer and use it in GitHub Desktop.
Save Shoora/6d4d6a009a2a975b0a40 to your computer and use it in GitHub Desktop.
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