简体   繁体   English

如何检查DOM元素是否已完全加载?

[英]How to check if DOM element is fully loaded?

I'm loading really big web page with thousands of elements. 我正在加载包含数千个元素的非常大的网页。 How can I test if node has fully loaded including it self and all it child elements but I don't want to wait for whole page to be loaded. 如何测试节点是否已完全加载,包括它自身和所有子元素,但我不想等待整个页面被加载。 For example lets have this page: 例如,让我们拥有此页面:

 <html> <head> <script> var cnt = 0; var id = setInterval(function test() { var e = document.querySelector('#content') if (!e) return; // how to test is "e" fully loaded ? if (cnt == e.childNodes.length) { clearInterval(id); } else { cnt = e.childNodes.length; console.log(cnt); } }, 10); </script> </head> <body> <div id="content"> <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div> <!-- ... add 30k div elements --> </div> </body> </html> 

This will print something like this on console: 这将在控制台上打印如下内容:

 4448 9448 14448 19448 24948 30000 

say you want to alert after the div#content is loaded. 说您要在div#content加载后发出警报。 if you put your javascript after div's closing tag, it will run after loading all the html prior to the script. 如果您将javascript放在div的结束标记之后,它将在加载脚本之前的所有html后运行。

<div id="content">
    // your content
</div>
<script type="text/javascript">
    alert("finished loading until this point");
</script>

I think that the load event would be an more apropriate answer to your question. 我认为load event将是您问题的更恰当答案。 It can be atached to an ellement and fires when everything is loaded including images and other resources. 加载所有内容(包括图像和其他资源)时,它可能会变得很麻烦并触发。

some examples you can find here. 您可以在此处找到一些示例。

https://developer.mozilla.org/en-US/docs/Web/Events/load https://www.w3schools.com/jsref/event_onload.asp https://developer.mozilla.org/zh-CN/docs/Web/Events/load https://www.w3schools.com/jsref/event_onload.asp

but if you don't care about the resources than you might want to look at this. 但是如果您不在乎资源,那么您可能不妨看一下。

https://developers.google.com/speed/docs/insights/rules https://developers.google.com/speed/docs/insights/rules

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM