-
-
Save buzzedword/1027609 to your computer and use it in GitHub Desktop.
Super tiny JS loader
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
// {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; | |
}; |
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
Micro optimizations FTW!