简体   繁体   中英

How can you tell when a dom node gets added to the document?

Is there any good way to get alerted when a dom node is added to the document? If you're putting together dom nodes in javascript, usually you put them together leaves-first, so that you're not reflowing all the time. But this means that when elements are added, they aren't visible on the page, which means certain information about them is inaccessible/wrong. For example offsetWidth will be 0 before its added to the document's flow, regardless of its width after its added.

So I would ideally like some way to get an event when a node is added to the document so I can then do things that require offsetWidth and other things like that that require it to be rendered.

Using a mutation observer to observe document should be a reasonable tool to use in most cases (it might not be reasonable if you're setting up a listener intended to listen for a long period of time):

        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if(mutation.target.contains(block.domNode)) {
                    // do your thing, then..
                    observer.disconnect()
                }
            })
        })
        observer2.observe(document, {childList: true, subtree: true})

Note that if the dom node is removed from the document, then reinserted, the above code will not catch that (but could be modified to).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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