patternjavascriptMinor
What is the shortest snippet that emulates `include` in JavaScript without third-party scripts?
Viewed 0 times
snippetwithoutthethirdscriptsshortestwhatjavascriptincludeemulates
Problem
JavaScript doesn't offer a module system. There are many third-party solutions, like
The .js file should look like this, for example. Notice the addition is just a small one-liner:
For clarity, the top function above, expanded, is equivalent to:
Can this be minimized even further?
require.js or jQuery's $.getScript. Most, while good, they bring dependencies, extra kbs and/or limit your folder structures. Sometimes it's necessary to make a .js file self-sufficient. This said, what is the smallest snippet that can be inserted at the top of a .js file, which will emulate "import", so it can load other scripts before running itself?The .js file should look like this, for example. Notice the addition is just a small one-liner:
(function(i,m,p,o,r,t){for(p=i.length,o=0;o<p;++o){r=(t=document).createElement('script');r.src=i[o];r.onload=function(){!--p&&m()};t.head.appendChild(r); }; })
(['http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js','http://underscorejs.org/underscore-min.js'],
function main(){
console.log('jQuery loaded:',$);
console.log('underscore.js loaded:',_);
});For clarity, the top function above, expanded, is equivalent to:
(function (u, f, l, i, a, d) {
for (l = u.length, i = 0; i < l; ++i) {
a = (d = document).createElement('script');
a.src = u[i];
a.onload = function () {
!--l && f()
};
d.head.appendChild(a);
};
})Can this be minimized even further?
Solution
Here is what I do:
I should mention that in production I pretty much always combine all javascript files into one larger, minified, and google closure compiled file.
var a_script= document.createElement('script');
a_script.src = 'http://www.blah.com/some_script.js';
document.head.appendChild(a_script);I should mention that in production I pretty much always combine all javascript files into one larger, minified, and google closure compiled file.
Code Snippets
var a_script= document.createElement('script');
a_script.src = 'http://www.blah.com/some_script.js';
document.head.appendChild(a_script);Context
StackExchange Code Review Q#18973, answer score: 2
Revisions (0)
No revisions yet.