How do you load one JavaScript file from another JavaScript file, like CSS?
In CSS we use write @import url(\"mycss.css\");.
Is there any way to do it i
Just because no-one has mentioned it yet, there's another option, which doesn't require any fancy libraries or tricky coding, document.write. In principal, it would look like this, although see below for a caveat:
document.write('');
This will be executed upon completely parsing the script tag, and if you put your script tag in the head, the new script tag will also be in the head, right after the one being executed. Take care to execute it directly rather than when the document has been loaded (as in a $(function(){}) callback. This is what I use:
(function(){
function load(script) {
document.write('<'+'script src="'+script+'" type="text/javascript"><' + '/script>');
}
load("script1.js");
load("script2.js");
load("etc.js");
})();
The enclosing function is just there to not pollute the global namespace.
The caveat (and why the 'script' that is broken up above) is that there may be no ending script tags within a script tag, the HTML parser doesn't know it's part of the script. There's an other question on that subject.