Reputation: 1623
I was wondering if there was a way to include a js file in another js file so that you can reference it. What I'm asking for is the JS equivalent of include()
in PHP.
I've seen a lot of people recommend this method as an example:
document.write('<script type="text/javascript" src="globals.js"></script>');
But I'm not sure if that's the same as include()
Upvotes: 1
Views: 134
Reputation: 885
Don't use document.write, it could wipeout the entire page if the page has already written. You can write something simple like this:
var jsToInclude = document.createElement('script');
jsToInclude.type = 'type/javascript';
jsToInclude.src = '/dir/somefile.js'; // path to the js file you want to include
var insertionPointElement = document.getElementsByTagName('script')[0]; // it could be the first javascript tag or whatever element
insertionPointElement.parentNode.insertBefore(jsToInclude, insertionPointElement);
Upvotes: 1
Reputation: 311
Check out http://requirejs.org/ . You can define (AMD) modules and reference them in other modules like so
define(["path/to/module1", "path/to/module1")], function(Module1, Module2) {
//you now have access
});
Upvotes: 2