czv
czv

Reputation: 61

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

Upvotes: 6

Views: 10828

Answers (2)

Jos Luijten
Jos Luijten

Reputation: 679

I think that the load event would be an more apropriate answer to your question. 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

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

Upvotes: 0

Emre T&#252;rkiş
Emre T&#252;rkiş

Reputation: 1002

say you want to alert after the div#content is loaded. if you put your javascript after div's closing tag, it will run after loading all the html prior to the script.

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

Upvotes: 1

Related Questions