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()
asked Feb 13, 2014 at 16:11
-
2look for "javascript modules", there are a few common solutions (asm, browserify, require.js).Denys Séguret– Denys Séguret2014年02月13日 16:12:47 +00:00Commented Feb 13, 2014 at 16:12
-
2possible duplicate of How to include a JavaScript file in another JavaScript file?Maykonn– Maykonn2014年02月13日 16:13:03 +00:00Commented Feb 13, 2014 at 16:13
2 Answers 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
});
answered Feb 13, 2014 at 16:18
Sign up to request clarification or add additional context in comments.
Comments
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);
Comments
lang-js