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?
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.
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.
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.
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With