javascriptfunction

Why my function in Javascript is not working?


I am trying differents methods to implement a function, but one o them isn't working. Are this syntax correct?:

function funcao2()
        {
            alert('Tudo bem?');
        }funcao2();

I have a 'self invoking function', an 'anonymous function' and a 'function attributed to a variable', but the second aren't working. See the code:

    //Função de auto-invocação anônima ou função recursiva anônima
    (function(){
        alert('Oi');
    })();
    //Função anônima
    document.onload = function(){
        alert('Página carregada');
    };
    //Atribuir função a uma variável e executá-la em seguida
    var funcao = function(){
        alert('Oi novamente');
    }; funcao();

Solution

  • Commented this, seems to be what the OP wanted to know, so posting it as an answer:

    document.onload should be window.onload, document has the onreadystatechange event, the window loads

    related:

    when using the document.onreadystatechange event, check the status and readystate properties:

    document.onreadystatechange = function(e)
    {
        if (this.readyState === 4 && this.status === 200)
        {
            //only now, the document is loaded
            return;
        }
        //do stuff on readyState 1,2,3... <-- usefull when loading is likely to fail
    }