Bernd Wechner
Bernd Wechner

Reputation: 2143

Javascript: Make DOM changes and know when rendering of them is complete?

If I insert a rather large element in Javascript I'd like to know when it's finished rendering.

It turns that if I check document.readyState it is "complete" even though the render has not even started. That is something like this:

ElementInMyDOM.appendChild(LargeHTMLElement);
console.log(`Document Ready State: ${document.readyState}`)

prints "Document Ready State: complete" to the console well before the LargeHTMLElement is rendered. So that's a fizzle.

I could use a MutationObserver (and in fact I do, and that works nicely as the handler is called after it's rendered, but this question arises out of a desire to find an alternative if it exists too). Essentially I'm curious if there is either:

  1. Some other property of the document than readyState that tells us if the DOM is truly rendered or not.
  2. Some other callback that is more specific than a MutationObserver to receiving a callback when rendering of changes to the DOM are complete (when the DOM and what's rendered are the same).

It's possible that the answer is, no, there is no such thing. But I'd like to think there is, as a MutationObserver is a little more general than needed, as I'm not after any mutation I just want to insert an element and know when it's finished rendering.

Javascript is generally very good at providing many possible ways to achieve one outcome ;-)

Upvotes: 1

Views: 1027

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

There's no requestPostAnimationFrame yet, unfortunately.

With requestAnimationFrame, you can queue a task just before a repaint occurs. If the task itself queues a setTimeout, that timeout callback can run right after repainting is done.

ElementInMyDOM.appendChild(LargeHTMLElement);
requestAnimationFrame(() => {
  setTimeout(() => {
    console.log('Initial rendering of LargeHTMLElement done');
  });
});

This will also wait for all other pending elements to be painted/repainted as well.

Upvotes: 4

Related Questions