有一个https://stackoverflow.com/questions/32656594/domcontentloaded-blocks-page-loading没有被解析。
当侦听DOMContentLoaded的处理程序可以阻止第一次绘制时,我遇到了一种情况。有时它会阻塞,有时它不会
我试过很多次cmd +R来看它。对这种行为有什么解释吗?
另外,我录制了一段视频,显示如下:https://www.youtube.com/watch?v=EDZQ1nLCK2w&feature=youtu.be
window.addEventListener('DOMContentLoaded', () => {
let i = 0;
while (i++ < 1000000000) {
continue;
}
document.getElementById('el').remove();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="el">Some text</p>
</body>
</html>
发布于 2022-01-23 04:28:16
我想通了。眨眼呈现引擎中有一个错误,它同步地分派DOMContentLoaded事件。
// #blink/renderer/core/dom/document.cc
// #blink::Document::FinishedParsing
// FIXME: DOMContentLoaded is dispatched synchronously, but this should be
// dispatched in a queued task, see https://crbug.com/425790
if (document_timing_.DomContentLoadedEventStart().is_null())
document_timing_.MarkDomContentLoadedEventStart();
DispatchEvent(*Event::CreateBubble(event_type_names::kDOMContentLoaded));
if (document_timing_.DomContentLoadedEventEnd().is_null())
document_timing_.MarkDomContentLoadedEventEnd();
SetParsingState(kFinishedParsing);
**为什么有时是异步发送的,我不知道。现在,在我这一边,它总是同步的(在提出问题的时候可能还有一个bug )
发布于 2020-07-28 04:37:20
这是比赛条件。有时,在添加侦听器之前,文档已经加载/交互。
通过检查文档的readyState:document.readyState,可以看出两者之间的区别。您的代码没有运行,因为有时状态已经是interactive
或complete
,这意味着在实际添加侦听器之前DOMContentLoaded
事件已经启动。
处理这个问题的方法应该是这样的:
function init() {
let i = 0;
while (i++ < 1000000000) {
continue;
}
document.getElementById('el').remove();
}
if (document.readyState === 'loading') {
// Document not yet loaded, so wait for it.
window.addEventListener('DOMContentLoaded', init);
} else {
// Document is ready (interactive or complete), so call init immediately.
init();
}
https://stackoverflow.com/questions/63094476
复制相似问题