Why is the document.onreadystatechange function executed in advance?

console.time('onload')
console.time('onreadystatechange')
window.onload = ()=>{console.log('onload'); console.timeEnd('onload')}
document.onreadystatechange = ()=>{console.log('onreadystatechange');console.log(document.readyState);console.timeEnd('onreadystatechange')}

I wrote the above code in an inline script, why the result is the following?

In theory, console.time('onreadystatechange') should be executed first, but from the results, the onreadystatechange event is executed first, and document.readyState is ‘complete’, why is the event advanced?

>Solution :

There will be other state changes before document.readyState becomes complete.

At that time, the onreadystatechange function will be triggered.

console.timeEnd('onreadystatechange') is used in onreadystatechange.

When console.timeEnd is called, the timer corresponding to this record is cleared.

So when the subsequent onreadystatechange function is called again, there will be a prompt because there is no restart to set the onreadystatechange timer.

The entire execution sequence is consistent with the standard definition, and there is no problem.

Leave a Reply