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

2

2 Answers 2

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
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.