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;
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With