4

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
czv
  • 41
  • 1
  • 2
  • 1
    The only thing that would come into my mind is to have a check like this `div.nextSibling != null || documentIsReady` and observer for changes in the DOM using `MutationObserver` or if not supported `setInterval`. – t.niese Mar 07 '15 at 16:34
  • Similar (not same) question https://stackoverflow.com/questions/4057236/how-to-add-onload-event-to-a-div-element and answer https://stackoverflow.com/a/41176554/14824067 . – LuckyLuke Skywalker Apr 22 '22 at 09:41
  • Check with a MutationObserver for when the next sibling element is loaded. When the next sibling element is loaded, then the preceeding element and its children have been implicity loaded. – Damien Aug 05 '23 at 04:52

2 Answers2

1

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

Jos Luijten
  • 621
  • 5
  • 9
0

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>
Emre Türkiş
  • 992
  • 9
  • 23
  • Thank you for answer but the problem is that I don't have page control, I'm basically injecting my javascript code into external page while it is loading. – czv Mar 07 '15 at 22:12
  • can you please explain how you're injecting your code, i didn't get that from the original question. maybe we can help more correctly – Emre Türkiş Mar 08 '15 at 00:11
  • @t.niese answered in quesion's comment – czv Mar 08 '15 at 02:06