为什么 document.onreadystatechange 运行两次

Why document.onreadystatechange runs twice?

本文关键字:两次 document onreadystatechange 运行 为什么      更新时间:2023-09-26

>我在下面有下面的例子。我很好奇为什么控制台日志两次写入"文档已准备就绪"行(在 FF 和 Chrome 中)。如何确保它只运行一次?

附加

问题:由于我也在使用已经附加了事件的window.onload,是否可以在不删除以前分配的事件的情况下添加窗口事件?

<!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>

它运行多次,因为它有多个状态

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

loading, interactive, complete

如果您只想捕获其中一个,只需使用类似于您在链接中看到的代码对其进行过滤