Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How dos XHR's "readyState==3" work?

Here's the code snippet

xhr.onreadystatechange = function(){ 
   if(xhr.readyState == 3){
      console.log("readyState response length " + xhr.response.length);
   }
} 

And the console is

readyState response length: 3854 
readyState response length: 33214 
readyState response length: 35296 

I don't know what's the timing of onreadystatechange firing, it does seems a bit related to the size of response,how does it work?

like image 664
Lanston Avatar asked Dec 02 '25 05:12

Lanston


1 Answers

What is XHR readyState=3?

Having the readyState with a value of 3 it means that the current state is LOADING.

So when is a readyStateChange event for that state fired?

Whenever an asynchrounous request does switch to the LOADING state. That is especially triggered by:

Once the first byte (or more) of the response entity body has been received […] or If there is no response entity body […] Then switch to the LOADING state.

So browsers are free to fire this event with readyState 3 when they receive bytes of the response. Some trigger it more often (at every buffer flush), other's dont. The spec even says for the readystatechange Event:

The readyState attribute changes at some seemingly arbitrary times for historical reasons.

like image 50
Bergi Avatar answered Dec 03 '25 19:12

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!