Include a JavaScript file in another JavaScript file?

s there something similar to @import in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?

asked May 19, 2015 in JAVASCRIPT by rajesh
0 votes

1 Answer

0 votes
JavaScript has no import, include, or require. There are other ways for JavaScript to include external JavaScript contents, though.

Ajax Loading

Load an additional script with an Ajax call and then use eval. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs and hacks.

jQuery Loading

The jQuery library provides loading functionality in one line:

$.getScript("my_lovely_script.js", function(){

   alert("Script loaded and executed.");

   // Use anything defined in the loaded script...
Dynamic Script Loading

Add a script tag with the script URL in the HTML. To avoid the overhead of jQuery, this is an ideal solution.

The script can even reside on a different server. Furthermore, the browser evaluates the code. The