1

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()

beckah
  • 1,543
  • 6
  • 28
  • 61
  • 2
    look for "javascript modules", there are a few common solutions (asm, browserify, require.js). – Denys Séguret Feb 13 '14 at 16:12
  • 2
    possible duplicate of [How to include a JavaScript file in another JavaScript file?](http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-file) – Maykonn Feb 13 '14 at 16:13

2 Answers2

2

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
});
michael truong
  • 321
  • 1
  • 4
1

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);
Lance
  • 865
  • 8
  • 19