user2613946 user2613946 - 1 year ago 85
Javascript Question

Why do we write onload() function before we write send() in XMLHttpRequest

I am new to XMLHttpRequest. I dont understand why do we write onload() function before send() function. onload() function process the response what we receive and send() function sends a request to server. So onload() has to be written after send() function as per my understanding. Can somebody help to understand this.

var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';

xmlhttp.open(method, url, true);
xmlhttp.onload = function () {
// Do something with the retrieved data
};
xmlhttp.send();

Answer Source

I dont understand why do we write onload() function before send() function.

So that the load handler is in place before the request is sent, since sending the request will result in calling the handler (if successful).

onload() function process the response what we receive and send() function sends a request to server. So onload() has to be written after send() function as per my understanding.

It's called after send is called (by the XHR infrastructure) (or potentially during). When you assign it to onload, you're not calling it. You're just defining it so that it's there when XHR needs to call it.

Here's what happens:

  1. You create the XHR.
  2. You register a handler for its load event (in your case, by assigning a function to onload).
  3. You call send.
    1. The browser starts (and potentially finishes) the request
  4. When the request finishes, if it's successful, the browser's XHR handling triggers the load event. That looks for any currently-registered handlers for load and queues calls to those handlers, if any. Those calls are run as soon as the main JavaScript thread is available to run them.

Very often, you'd get away with doing it the wrong way around because by the time the request completes, you'll have put the load handler there; but not always. load is an event. If the request can be satisfied immediately (for instance, from cache), the browser could fire load during send, and look to see if there's any load handler during the call to send, and if there isn't, not queue a call to any callback. Later when you attach a handler, the event has already been fired (when none were attached).

So you have to attach the handler before calling send.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download