How to share functions between javascript files?

Asked

Viewed 664 times

3

I have two files JavaScript.

arquivo1.js

function teste()
{
alert("fui chamado!");
}

In the arquivo2.js i would like to have access to function teste() of arquivo1.js without having to make the reference within the HTML.
That’s possible?

  • You can use a module manager such as Requirejs. This will require you to change file 1 to make it compatible.

  • Similar or duplicated to: http://answall.com/q/63389/129 ?

  • Sorry @Sergio but the link you showed is a good alternative for those who want to create a universal variable for example, but in my case, I want to be able to control which file will have access to the functions of the other.

  • @bfavaretto you would have some example of use in English?

  • I have nothing to recommend, but Google brings several tutorials. This one looks like one of the most complete: http://www.devmedia.com.br/standardizca-com-iife-amd-e-requirejs/31031 (warning: I have not read, I do not guarantee the quality).

  • By not referencing in HTML you delete the possibility to create the reference dynamically? You can add the script arquivo1.js creating a tag <script> in the arquivo2.js and dynamically insert it into the page.

  • @Marcusvinicius This is possible, but it is necessary to wait for the other file to load before having access to the functions inside it (the loading is asynchronous).

  • Yes, @bfavaretto. It is possible to make one script "wait" for the other using callbacks in the event onload of the created script element.

  • 1

    @Marcusvinicius By the way, that’s basically what Requirejs does :)

  • @Jedaiasrodrigues: a while ago I "hunted" the function inside the other file via xmlhttprequest using an intermediary php that returned the function as String to be executed as code. At the time I had compatibility problems, maybe things are better today. It will be a great resource to develop in Javascript background!

  • Thank you all for your help, I really liked the reply posted by @Marcusvinicius but unfortunately now I have problems precisely in the issue of asynchronous.

Show 6 more comments

2 answers

4

The simplest way is to include archive1 before archive2 in your HTML:

<!doctype html>
<html>
<head>
    <script src="arquivo1.js"></script>
    <script src="arquivo2.js"></script>
</head>

All globes defined in archive1 will be visible in archive2.

A slightly cleaner way to do this is to write archive1 so that only a global one is exported:

var LIB = {};

(function(){

   var msg = "fui chamado";

   var funcao_interna(){
       alert("oi");
   }

   LIB.teste = function(){
       alert(msg);
   }

   LIB.teste2 = funcao_interna;
}());

And in file 2 you do

LIB.teste();

That one (function(){ ... }()) is an "immediately invoked function" and is a trick that is used in Javascript to control the scope of variables. All variables and functions declared inside, such as msg and funcao_interna shall not be visible from outside.


Another way you can write is like this:

var LIB = (function(){

    function teste(){ alert("chamou") }

    return {
       teste:teste
    }
}());
  • That would be the same as window.LIB = (function(){ /* funções */ })();?

  • I thought the same thing as @re22

  • 1

    @re22: More or less. If you return an object with the functions exported from the IIFE then it works (see my edition)

4


You can dynamic load the script by creating a tag scriptand insert it into the page. For example:

Arquivo1.js

function Script1() {
    this.DigaOla = function() {
        alert("Sou do script 1");
    }
};

Arquivo2.js

 function loadScript(url, callback) {    
     var head = document.getElementsByTagName('head')[0];
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.src = url;    
     script.onreadystatechange = callback;
     script.onload = callback;

     head.appendChild(script);
 }

 $(document).ready(function() {
    loadScript("Arquivo1.js", function() {               
        var s = new Script1();
        s.DigaOla();
    });
 });
  • There’s only one problem @Marcusvinicius because if I add something after loadScript, like along those lines it is executed before the function is finished! In this case, what to do?

  • There’s not much to do but put all the code as callback’s loadDependency that you created. I made a sketch of your code, take a look.

  • Thank you very much my friend, I could have made an amendment proposal to register your authorship. With Fork unfortunately I can’t keep your credits.

  • No problem, if you want to do the pull request.

  • Please @Marcosvinicius I will feel better if you pull request. Thanks again.

  • 1

    It’s done, thanks for letting me contribute. If you need help.

Show 1 more comment

Browser other questions tagged

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