Reputation: 6035
Try running the following code in window.onLoad
:
var n = 0;
var N = 75000;
while (n < N)
{
span = document.createElement("span");
span.innerHTML = "0";
document.body.appendChild(span);
n++;
}
console.log("Finished.");
You should find that "Finished" appears in your console several seconds before the span tags appear in your browser. If not, try increasing N
by a few orders of magnitude.
How can I make DOM changes, and detect the moment at which not only the changes are complete, but are rendered on-screen?
I tried a MutationObserver, but it also gets notified several seconds before the changes appear onscreen. You can see that in this fiddle.
Upvotes: 3
Views: 1114
Reputation: 14561
I have little experience with such operations, but 5 minutes of experimentation with requestAnimationFrame
suggests that it might be useful for such use-case.
According to MDN:
The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
So I had a hunch that if a particular render took too long, the next call to the callback passed into requestAnimationFrame
would be delayed.
I have added a div (id = "loading"
) to your fiddle, which is visible initially. After appending all the nodes to DOM, I pass a callback to requestAnimationFrame
that would hide the #loading
div from the screen.
var loading = document.getElementById("loading");
// Update DOM ...
requestAnimationFrame(function() {
loading.style.display = "none";
});
You can take a look at the the fiddle here.
Upvotes: 1