Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Implement a Callback

Begana Choi
PLUS
Begana Choi
Courses Plus Student 13,122 Points

why this video used onload event instead of onreadystatechange?

and what's the difference between onroad and onreadystatechange?

2 Answers

the ready state will change several times before it actually finishes loading.

Onload only triggers once, when it's done loading.

ready state will trigger each time it goes up one level. These are the possible levels:

0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.

glad to help

Jennifer Ciaccio
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Ciaccio
UX Design Techdegree Student 11,137 Points

Before we had seen it as this done as if(xhr.onreadystatechange === 4){ code to be triggered when information is received back from server }

This should also trigger the function to trigger only once, when the AJAX call receives a response from the server correct? Or would that not be true in this instance? Would you be able to use either or?

You are correct Jennifer. The catch though is that the code does execute on each state change, and then the if() acts as a filter to run the code we want only once. So, yes the code inside the if does execute once, but the if had to run several times, one for each state change which is less efficient in terms of performance than the onload event, which triggers only once. End result is the same as you had noticed, but performance-wise, onload is a better choice.