Why is there a delay after xhr.upload.onload when POSTing files via XMLHttpRequest?

  • 0

    Actually, this is the essence of the question:
    When uploading files, at the stage xhr.readyState = 1 and after the occurrence of the event xhr.upload.onload , there is a delay, approximately equal to the time for uploading files ( xhr .upload.onprogress ).
    Files have been uploaded successfully (as indicated by the xhr.upload.onload event). And at this stage ( xhr.readyState = 1 ) we are not yet waiting for a response from the server, but are only getting ready to execute send () . Then, when something is loaded "there", statuses 2,3,4 are processed almost simultaneously.
    What might be happening at this moment?
    Or is it just that the API itself has been implemented in a moronic manner, and in fact 100% loading does not mean 100% preparation of files for sending ( send () )? It turns out that the download progress bar has reached 100%, but in fact, the sending stage will not come soon ( xhr.readyState = 2 ).
    Just what's the point then in this xhr.upload.onprogress if it does not give me information that the current status / stage is about to be completed (when the progress bar approaches the end).
    JavaScript Anonymous, Apr 3, 2019

  • 1 Answers
  • 0
    Because first the request, and only then the response.

    Run: xhr.send (data); and in turn:

    // сначала ты
    xhr.upload.onprogress // загрузка на сервер
    xhr.upload.onload // загрузка на сервер завершена
    // потом сервер
    xhr.onreadystatechange // xhr.readyState === 2 // HEADERS_RECEIVED // получены заголовки ответа (и только)
    xhr.onreadystatechange // xhr.readyState === 3 // LOADING // загрузка ответа сервера
    xhr.onprogress // загрузка ответа сервера
    xhr.onreadystatechange // xhr.readyState === 4 // DONE
    xhr.onload // загрузка ответа сервера завершена
    Leo Pugh

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!