Doubt over parameters and call functions

5

I created a function in JavaScript that when executed creates a tag <script> in <head> that loads an external JavaScript file.

I want to make sure that after this tag is created, a second function located within that file that has just been loaded is called, but part of the name of that second function is the parameter of the first function. Here is an example:

I start by creating the tag <script> :

function funcao_um (parametro) {
    var script = document.createElement('script');
    script.src = 'nomeDoArquivo.js';
    document.getElementsByTagName('head')[0].appendChild(script);

Now that it is created, within that same function I want to call another function called "funcao_parametro();" , which is in the .js file that just was loaded.

I have tried to use several codes like return "funcao_" + parametro + "();" and even the so controversial eval , in fact, I tried anyway and I could not, or Chrome says that the function is not defined or the whole script does not work. Could you please help me? I'm new to JavaScript and I have no idea how to do this.

Note: I'm sure the other JS file is OK, so the problem is not in it.

    
asked by anonymous 13.06.2014 / 01:24

4 answers

4

Let me see if I understand: you want to call a function (preload loaded!) whose name you have in the form of a string, right?

Just use the window object!

Let's use the foo function as an example:

function foo() {
    alert('foo!');
}

The foo function is a property of the window object. That is, there are three ways to call this function:

  • Only foo() .
  • More completely: window.foo() .
  • Or: window['foo']() .

Notice that in the third example we use a string with the name of the method ( foo ). Remember that, roughly speaking, a JavaScript object is just a "big hashmap".

The third example would suit you!

Why eval did not work?

Following the example above,% wont work. I can not tell you why in your case it did not work ...

Of course, I will not go into the discussion of not using the eval('foo()') function because you have already demonstrated a little understanding about it (:

p.s .: consider doing otherwise

Using the name of a reference to be called programmatically can mean a difficult maintenance and / or confusing code (especially if the code grows).

Remember that in JavaScript functions are first-class citizens . That is, functions can be returned and assigned to variables:

function obterAcao() {
    return function() { alert('ação!'); }
}

var acao = obterAcao();
//...
acao();

Perhaps using functions in this way will make your code more readable and maintainable. This is the tip.

    
13.06.2014 / 02:58
2

You're doing it right. Only missing this:

script.setAttribute('type','text/javascript'); 

to tell the Browser what kind of content it is.

Take a look at this example and notice that the alert pops up twice. One when it loads, and another one after 5 seconds, because the newly inserted function is now present / in the scope of the code.

function funcao_um(parametro) {
    var script = document.createElement('script');
    script.setAttribute('type','text/javascript'); 
    script.src = 'https://rawgit.com/SergioCrisostomo/version-files/master/soPT_script1.js';
    document.getElementsByTagName('head')[0].appendChild(script);
}
funcao_um();
setTimeout(function(){
  dentroDoScript();
}, 5000)

And inside the external file I have this:

function dentroDoScript(){
     alert('Estou vivo!');
}
dentroDoScript();
    
13.06.2014 / 01:42
2

To include a script dynamically, use the following function:

function include(url, callback, conteudo) {
    var script = document.createElement('script');

    script.type = 'text/javascript';
    script.async = 'async';
    script.defer = 'defer';
    script.src = url;
    if (conteudo) script.innerText = conteudo;

    if (script.readyState) {
        script.onreadystatechange = function () {
            if (script.readyState === 'loaded' || script.readyState === 'complete') {
                script.onreadystatechange = null;
                callback && callback();
            }
        }
    }
    else {
        script.onload = callback;
    }

    document.body.appendChild(script);
}

And use it like this:

include('/meuscript.js', function() {
    // código aqui
});

Another example, loading jQuery dynamically:

include('http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js', function() {
    alert($('body').html());
}); 
    
13.06.2014 / 01:48
2

If the second function is in global scope, just invoke it from the window object. Also remember to wait for the script to load as indicated in the other responses:

function funcao_um (parametro) {
    var script = document.createElement('script');
    script.src = 'nomeDoArquivo.js';
    document.getElementsByTagName('head')[0].appendChild(script);
    script.onload = function() {
        // invoca a função do segundo arquivo
        window["funcao_" + parametro]();
    }
}
    
13.06.2014 / 02:15