Reputation: 8919
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 in JavaScript?
Upvotes: 31
Views: 57899
Reputation: 1476
There's no @import-ish function/method in Javascript, but you can simply append a script to the <head>
tag like so:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/path/to/js/file';
document.getElementsByTagName('head')[0].appendChild(newScript);
Or like Edgar mentioned right before me you can use jQuery.
Upvotes: 53
Reputation: 18344
Yes. If you want in pure JavaScript, you have to create dynamically a script
tag, and append it to the document.
Yes. If you use the jQuery library, you can use the $.getScript
method.
$.getScript("another_script.js");
Upvotes: 33
Reputation: 35657
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('<script src="myscript.js" type="text/javascript"></script>');
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.
Upvotes: 19
Reputation: 4944
Javascript itself doesn't provide any help with modularization other than the ability to eval
a string. But this is a common-enough need that most big javascript frameworks have come up with their own solutions, and more recently, there has been an effort to standardize those APIs in the requirejs project. If you're using a framework like Dojo or jQuery, you're probably just best off learning to use their facilities, but if not, requirejs
is a lightweight standalone tool. You basically just add
<script data-main="scripts/main" src="scripts/require.js"></script>
to your <head>
section, and then put your own javascript inside some wrapper code like this (stolen from the require.js
site):
require(["helper/util"], function() {
//This function is called when scripts/helper/util.js is loaded.
require.ready(function() {
//This function is called when the page is loaded
//(the DOMContentLoaded event) and when all required
//scripts are loaded.
});
});
Upvotes: 6