Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .js file "include" another .js file [duplicate]

In PhP you can.

In html, you sort of can with <script src="..."> tag

but what about if we have a .js file and we want to include another .js file. How would we do so?

like image 559
Septiadi Agus Avatar asked Apr 29 '13 15:04

Septiadi Agus


People also ask

Can a JS file include another JS file?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

Can you have multiple JS files?

You can write your JS in separate files, but when it comes to deploying, it's more efficient to minify them all into a single file. For each script you load in your browser, you make a round-trip to the server, so it makes sense to minimize those.

Should all my JavaScript be in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.


1 Answers

If you mean in a browser context, not directly, but you can use a loader like at RequireJS (there are several).

Or to do it manually:

var script = document.createElement('script'); script.src = "/path/to/the/other/file.js"; document.getElementsByTagName('script')[0].parentNode.appendChild(script); 

Note, though,that with the above the functions and such in the other file won't be available for use right away. The code above starts the process of loading the file, but it continues asynchronously. You can use events to know that the load is complete (primarily the load event, but on older versions of IE you have to use onreadystatechange -- this is one reason people use loaders!).

like image 147
T.J. Crowder Avatar answered Oct 07 '22 23:10

T.J. Crowder