Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there 'element rendered' event?

Tags:

javascript

dom

I need to accurately measure the dimensions of text within my web app, which I am achieving by creating an element (with relevant CSS classes), setting its innerHTML then adding it to the container using appendChild.

After doing this, there is a wait before the element has been rendered and its offsetWidth can be read to find out how wide the text is.

Currently, I'm using setTimeout(processText, 100) to wait until the render is complete.

Is there any callback I can listen to, or a more reliable way of telling when an element I have created has been rendered?

like image 628
funkybro Avatar asked Apr 08 '13 09:04

funkybro


1 Answers

The accepted answer is from 2014 and is now outdated. A setTimeout may work, but it's not the cleanest and it doesn't necessarily guarantee that the element has been added to the DOM.

As of 2018, a MutationObserver is what you should use to detect when an element has been added to the DOM. MutationObservers are now widely supported across all modern browsers (Chrome 26+, Firefox 14+, IE11, Edge, Opera 15+, etc).

When an element has been added to the DOM, you will be able to retrieve its actual dimensions.

Here's a simple example of how you can use a MutationObserver to listen for when an element is added to the DOM.

For brevity, I'm using jQuery syntax to build the node and insert it into the DOM.

var myElement = $("<div>hello world</div>")[0];  var observer = new MutationObserver(function(mutations) {    if (document.contains(myElement)) {         console.log("It's in the DOM!");         observer.disconnect();     } });  observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});  $("body").append(myElement); // console.log: It's in the DOM! 

The observer event handler will trigger whenever any node is added or removed from the document. Inside the handler, we then perform a contains check to determine if myElement is now in the document.

You don't need to iterate over each MutationRecord stored in mutations because you can perform the document.contains check directly upon myElement.

To improve performance, replace document with the specific element that will contain myElement in the DOM.

like image 185
Elliot B. Avatar answered Nov 16 '22 02:11

Elliot B.