Skip to content

Instantly share code, notes, and snippets.

@buzzedword
Forked from qwertypants/loadjs.js
Created June 15, 2011 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzzedword/1027609 to your computer and use it in GitHub Desktop.
Save buzzedword/1027609 to your computer and use it in GitHub Desktop.
Super tiny JS loader
// {String} f File name
// {Boolean} c Condition
// {undefined} [l,j,s] Shortcut for var.
var loadjs = function(f,c,l,j,s,a) {
a = ((typeof f == 'object')? f : []);
f = ((typeof f == 'undefined') ? '' :
((typeof f == 'object') ?
((typeof f[0] !== 'undefined')? f[0] : '')
: f));
l = f.length;
if ( c && f.substring(l - 3, l) === ".js") {
j = document.createElement('script');
j.type = 'text/javascript';
j.src = f;
j.async = false;
s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(j, s);
}
if (a.length > 0) { a.shift(); loadjs(a,true); }
return j;
};
@qwertypants
Copy link

Micro optimizations FTW!

@buzzedword
Copy link
Author

TSH. the entire "check if j is undefined" was unnecessary-- it hasn't been added to the DOM yet, and createElement is a blocking operation. So, j is inherently completed by the time s has to execute. Twas no micro optimization!

Also, the var statements were litered through scopes and would have been hoisted anyway-- I bumped it to the top of the function, then optimized it further.

f would sometimes throw an error if there was nothing plugged in. for the purpose of not borking code, I fixed it to include a type comparison and defaults.

f also supports an array in the style of ['filename.js','filename.js'] to be input.

Finally, just for usability, we return the script element appended. Fun!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment