Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a JavaScript function

Tags:

javascript

To call, for example, a function named makeRequest, I learned you need to do makeRequest();. If you only do makeRequest; it is a reference to the function (I thought). Yet, looking at this code (which worked when I tested it), it calls makeRequest; on the window.onload without the parens.

Can someone explain?

window.onload = makeRequest;
var xhr = false;

function makeRequest() {
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) { }
        }
    }

    if (xhr) {
        xhr.onreadystatechange = showContents;
        xhr.open("GET", "colors.xml", true);
        xhr.send(null);
    }
    else {
        document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
    }
}

function showContents() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            var outMsg = xhr.responseText;
        }
        else {
            var outMsg = "There was a problem with the request " + xhr.status;
        }
        document.getElementById("updateArea").innerHTML = outMsg;
    }
}
like image 673
Leahcim Avatar asked Jan 20 '23 01:01

Leahcim


1 Answers

On this line:

window.onload = makeRequest;

the function makeRequest is not called. You only assign the function pointer to the onload event. When the DOM is loaded the browser automatically calls this event and it it is only at that moment that the function it is pointing to is invoked (which might happen much later but leave you with the impression that the function is called immediately).

like image 89
Darin Dimitrov Avatar answered Jan 31 '23 05:01

Darin Dimitrov