Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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;

This comment has been minimized.

Copy link

@qwertypants qwertypants commented Jun 15, 2011

Micro optimizations FTW!


This comment has been minimized.

Copy link
Owner Author

@buzzedword buzzedword commented Jun 15, 2011

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
You can’t perform that action at this time.