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:
- You create the XHR.
- You register a handler for its
load
event (in your case, by assigning a function to onload
).
- You call
send
.
- The browser starts (and potentially finishes) the request
- 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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…