Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why document.onreadystatechange runs twice?

I have the following example below. I am curious why the console log writes the line 'document is ready' twice (both in FF as well as Chrome). How can I make sure it only runs once?

Additional question: since I am also using window.onload that already has an event attached, is it possible to add a window event without removing previously assigned ones?

<!doctype html>
<html>
    <head>
        <script>
            window.onload=function(){console.log('window is ready');}
            document.onreadystatechange = function(){console.log('document is ready');}
        </script>
    </head>
    <body>
        Hello
    </body>
</html>
like image 241
Patrick Avatar asked Oct 20 '25 14:10

Patrick


1 Answers

It runs multiple times because it have multiple states

https://developer.mozilla.org/en/docs/Web/API/Document/readyState

loading, interactive, complete

If you want to catch only one of them, just filter it using code similar to the one you see by the link

like image 58
llamerr Avatar answered Oct 22 '25 04:10

llamerr



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!