Search code examples
javascriptxmlhttprequest

Difference between onreadystatechange and onload


I tested two kinds of doing XHR:

1.

xhr.onreadystatechange = function() {

            if (this.readyState == 4 && xhr.status !== 500) {

                function getElementByXpath(path) {

2.

xhr.onload= function() {

                function getElementByXpath(path) {

and don't realized any difference. Could somebody point me to it? Or is there realy no one?


Solution

  • A readystatechange event fires every time the readyState changes (which is several times).

    A load event fires only when the request has completed successfully.

    In your example you add some extra tests to your readystatechange handler to test if it has reached the final state (4 (unless there are certain kinds of error in which case it will be 0)) and to make sure it isn't a 500 error. There are other errors which would not trigger a load event.