Is it possible to include a Javascript file within another Javascript file?

Asked

Viewed 19,859 times

5

You can include a Javascript file inside another Javascript file?

Similar to @import in CSS or to include of PHP?

5 answers

9


You can only include a script in an HTML page. knowing this you have some solutions to "simulate" the inclusion by javascript, as it would be?

In my index.html file I have my scripts.js file, in it I would like to load two other. clients.js and products.js so I do so:

Javascript-enabled:

var imported = document.createElement('script');
imported.src = 'cliente.js';
document.head.appendChild(imported); 

With jQuery:

$.getScript("produtos.js", function(){
   alert("Script loaded but not necessarily executed.");
});

There are other ways but they are just different ways to include javascript in html whether asynchronously or not.

Include a Javascript file in Another Javascript file?

  • 2

    But adding the script to HTML will not include the script within the other script - the added script will be executed in a global scope.

  • 3

    @Klaiderklai exactly, so it is important to be extra careful when performing this inclusion, and others, always be careful to avoid conflict by encapsulating the methods and variables.

2

Possible is, but this is not a native feature.

There are no @import, #include, include() or similar directives for Javascript.

What is possible to do (I consider gambiarra) is to create an element through Javascript code and assign to the content of this element the content of another file.

I do not recommend.

2

Allan, as Bruno has already mentioned, there is currently no native implementation that does include other files JS. but you can define your scripts as modules and use a library AMD to manage your scripts.

I would say use AMD in your project can be especially advantageous if you are developing an application SPA, but nothing prevents you from using this approach in a multi-page application.

Some examples of AMD Blibiotecas are:

Here is a small example from Github of RequireJS

HTML

<html>
    <head>
        <script data-main="app" src="lib/require.js"></script>
    </head>
    <body>
        <h1>Hello World</h1>
    </body>
</html>

Note that in the example, he just added the require.js and informed the *.js file that has the AMD configuration, in this case the app.js

app js.

requirejs.config({
    baseUrl: 'lib',
    paths: {
        app: '../app'
    }
});
requirejs(['app/main']);

here he set the path to the scripts, in case the folder lib and a path to the folder app, and started running the file app/main.js

app/main.js

define(function (require) {
    var messages = require('./messages');
    var print = require('print');

    print(messages.getHello());
});

here he reported that the script has two dependerias, app/messages.js and lib/print.js, in this case he will expect the two scripts are executed in order to continue.

lib/print.js

define(function () {
    return function print(msg) {
        console.log(msg);
    };
});

here has not much secret, we have only a function without dependencies.

app/messages.js

define(function () {
    return {
        getHello: function () {
            return 'Hello World';
        }
    };
});

same thing here, but an object is returned.

0

It is perfectly possible, create a file 'list.js' and do so:

import('assets/exemple.min.js')
import('assets/exemple2.min.js')
import('assets/exemple3.min.js')
import('assets/exemple4.min.js')
.then(module => {
        module.loadPageInto(main);
      });

Your files normally loaded as in a tag <script>, you can find other information in the documentation, access: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

0

Not while not implementing a method or statement. It is "ok" that is possible, in Javascript:

  • 1 . create an element script;
  • 2 . assign the src of script;
  • 3 . add the script for HTML;

Thus the content of an external file is requested, then it is interpreted and executed by the browser, but runs in a global scope, ie JavaScript will not be included within the other JavaScript. It’s a solution, but not how you want it.

  • I would not say that "it will never be possible", but rather that it is "very unlikely". If the question is why the language works with an interpreter and would need a compilation and analysis process for that, well ES6 itself has modules that work with static analysis (something similar to what would be necessary to make a #include in JS). So if the team that handles the Ecmascript specification wants to put this, it’s possible with the current features, but as I said, I find it very unlikely (and nothing useful, never needed to use)

  • @Gabrielkatakura I agree a little, but if you are going to add this #include will not work very well because the declared file has to load and will not run in the same scope. In CSS it makes more sense @include, even having to press, because in language there are no scopes.

  • Not exactly, it depends on how they would implement, nothing prevents them from implementing in a way that the scope is solved (or not). We are talking about an not implemented Feature, we cannot assume such limitations if when looking at the compiler/interpreter point of view this may be possible... but it would be too much work and as I said, I find it unnecessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.