How to import / include source files in JavaScript?

Possible duplicate:
How to include js file in another js file?

Suppose I have several JavaScript source files: a.js , a1.js and a2.js Functions a.js call functions from a1.js and a2.js

Now I have to declare all these files in my HTML page. I would like to declare only a.js in HTML and "import / include" a1.js and a2.js in the a2.js source file.

Does it make sense? Can I do this in JavaScript?

+8
javascript client-side
source share
3 answers

You cannot specify import in vanilla javascript.

So, your solutions (excluding a heavy server framework):

While you are not experiencing, and if the number of your files is small (less than 15), I recommend just choosing the first or second solution. Using a module loader can have side effects that you don't want to debug when you start learning javascript.

+8
source share

You can import:

 <script type="text/javascript"src="a1.js"></script> <script type="text/javascript"src="a2.js"></script> <script type="text/javascript"src="a3.js"></script> 

if you want to do this directly from JS, you can use Ajax, this post explains how: include-javascript-file-inside-javascript-file

+6
source share

You can link JavaScript files (as well as CSS) together using specific tools to reduce the number of files you need to include. It also increases page loading performance.

These tools combine multiple JavaScript files into a single JavaScript file (possibly minifying files as well) and multiple CSS files into a single CSS file. This results in fewer HTTP connections from the browser to the server, so there are fewer things to get in sequence.

ASP.Net MVC 4 has built-in support for this:

http://theshravan.net/bundling-and-minification-support-in-asp-net-mvc-4/

There are a number of solutions for other environments such as Juicer .

If you cannot combine all the resources (perhaps some of them belong to the CDN, while others are served locally), you can use the download manager, for example require.js .

+2
source share

All Articles