13

Is it possible to determine when setting an innerHTML has loaded? I'm not sure if it's a synchronous operation. I assume the 'building the DOM' is synchronous, but loading tags, contents, etc isn't.

So in a nutshell - is there a way to get an event when innerHTML has completed loading?

Thanks!

5
  • 2
    the innerHTML of what? the body, an element...
    – shawndumas
    Aug 9, 2011 at 19:01
  • 1
    innerHTML of any element. Imagine I have a big chunk of HTML I want to dump inside of a divs innerHTML
    – Steve
    Aug 9, 2011 at 19:08
  • This question is too vague. What do you mean by "completed loading"? I guess the answer will differ considerably depending on what type of content you inject. Images, scripts, stylesheets, Flash, applets, iframes, video, audio? Aug 10, 2011 at 19:08
  • The question should be asking whether there is a callback or Promise possible when repainting is finished after setting an innerHTML of any displayed element, for example in order to measure the height of the displayed HTML. Dec 16, 2022 at 0:27
  • See macarthur.me/posts/when-dom-updates-appear-to-be-asynchronous for a method to wait for repainting to complete after setting the innerHTML property. Dec 16, 2022 at 0:38

8 Answers 8

22

You need to use DOM Mutation Observers, which currently only work in Chrome and Firefox. They replace the performance-killing DOM Mutation Events.

Example code, from HTML5Rocks:

var insertedNodes = [];
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations) {
 mutations.forEach(function(mutation) {
   for (var i = 0; i < mutation.addedNodes.length; i++)
     insertedNodes.push(mutation.addedNodes[i]);
 })
});

observer.observe(document, { childList: true });
console.log(insertedNodes);

Here is the DOM4 spec. Please, don't use the setTimeout() hacks. :)

4

since img elements added through innerHTML do trigger their onload event you could add a tiny image at the end of your original code inserted in innerHTML, and in their onload event you could call a function. Also you can delete the image in there.

<img src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' onload='hasLoadedFunc();this.parentNode.removeChild(this);'>

JSFiddle sample

src='data:image' code is useful here since no specific image is needed.

I found this solution in another answer, I just can't find it. I will edit this solution once I find the reference.

2
  • Worked like a charm!!
    – m4heshd
    Jan 23, 2020 at 17:06
  • I want to insert text HTML, then wait until the height is known. Dec 16, 2022 at 0:29
2

It looks like @zahanm answer won't work if you replace the entire document HTML, which was what I needed. So I had to draw back to setInterval. Based on @shawndumas answer I've created a more modern approach using Promise:

function waitUntilSelectorExist(selector, interval = 100, timeout = 20000) {
    let intervalId;
    let elapsed = 0;

    let promise = new Promise(function(resolve, reject) {
        intervalId = setInterval(() => {
            let element = document.querySelector(selector);
            if (element !== null) {
                clearInterval(intervalId);
                resolve(element);
            }
            elapsed += interval;
            if (elapsed > timeout) {
                clearInterval(intervalId);
                reject(`The selector ${selector} did not enter within the ${timeout}ms frame!`);
            }
        }, interval);
    });

    return promise;
}

Also I use querySelector instead, so you can search for whatever selector you like, either .class, #id, etc.

If the function ever find the querySelector within the document the Promise will resolve, so you can use it with the new await keyword.

(async() => {
    try {
        await waitUntilSelectorExist("#test");
        console.log("Do stuff!");
    } catch (error) {
        console.warn(error); // timeout!
    }
})();

Of course you could also wrap around MutationObserver within a Promise if you are really just changing some elements within the document:

function waitUntilSelectorExist(selector) {
    let MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

    let promise = new Promise(function(resolve) {
        let observer;
        observer = new MutationObserver(function(mutations) {
            let element = document.querySelector(selector);
            if (element !== null) {
                observer.disconnect();
                resolve();
            }
        });
        observer.observe(document.body, { childList: true, subtree: true });
    });
    
    return promise;
}
4
  • This seems to wait for the DOM to update, which is always immediately, rather than waiting for rending (repainting) to finish, yes? Dec 16, 2022 at 0:31
  • The first approach is based on an interval, so it could randomly happen before or after rendering. The second approach will happen as DOM updates, so it won't wait the rendering process. Dec 16, 2022 at 2:00
  • But as @user123444555621 stated, capture the "onrendered" event is a vague requirement, you need to specify what you are expecting to be rendered for us to know what/if such event exists for the element you are expecting. Dec 16, 2022 at 2:29
  • It seems that the only solution for making measurements after an innerHTML call is to wait asynchronously, yielding the JavaScript thread back to the OS so that the browser can render and repaint the change. For this, two nested calls to requestAnimationFrame are advised. Events won't work until the JavaScript event loop is yielded. Dec 17, 2022 at 9:57
1
 var waitUntil = function (fn, condition, interval) {
    interval = interval || 100;

    var shell = function () {
            var timer = setInterval(
                function () {
                    var check;

                    try { check = !!(condition()); } catch (e) { check = false; }

                    if (check) {
                        clearInterval(timer);
                        delete timer;
                        fn();
                    }
                },
                interval
            );
        };

    return shell;
};

Use it like this:

waitUntil(
  function () {
    // the code you want to run here...
  },
  function() {
    // the code that tests here... (return true if test passes; false otherwise)
    return !!(document.getElementById('<id of the div you want to update>').innerHTML !== '');
  },
  50 // amout to wait between checks
)();
9
  • Thanks.. care to explain what premise this is based on? Your example is a bit hard to follow. Thanks!
    – Steve
    Aug 9, 2011 at 19:45
  • in the example i am sending two anonymous functions and an integer to the waitUtil function. the first function will run only when the second returns a true result. the integer is to set how long before the second function is run again (after it returned false).
    – shawndumas
    Aug 9, 2011 at 19:59
  • haha, I understood that part, but really what I was getting at fundamentally is why does, if return !!(document.getElementById('<id of the div you want to update>')); returns true, mean it is loaded? (How do you correlate a true return as it's loaded)
    – Steve
    Aug 9, 2011 at 21:09
  • the result of the getElementById will be null or a dom object. the former is falsey and the latter truthy. the !! does boolean coercion in js so the falsey value becomes false and the truthy true. if getElementById returns the dom object you are good to go. (but if you wanted to be pedantic you could do document.getElementById('theId').innerHTML)
    – shawndumas
    Aug 9, 2011 at 21:17
  • Sorry, I'm still not clear - in the example, is the div you are referencing the parent dive I inserted data into? (for example thisDiv.innerHTML). OR were you referring to a Div that would of been contained in the contents of the innerHTML? If the former, then I don't get why what you say is true. If the latter, then the issue is I may not know any of the Ids :(
    – Steve
    Aug 9, 2011 at 21:26
0

If your problem is waiting until innerHTML on an element has been completely rendered and painted, for example to measure the element's final size, use this code inside your top-level or async function:

await YieldForFrame();
await YieldForFrame();

where the following code is part of your program:

function YieldForFrame()
    {
    // Create Promise for use with 'await'
    return new Promise(function(resolve, reject)
        {
        requestAnimationFrame(resolve);
        });
    } // YieldForFrame
-2

Yes, you can do something like this:

window.document.getElementById("Testing").innerHTML = 
"<img src='test.jpg' width='200' height='400'>";
alert('test');

The javascript will be executed sequentially and therefore the alert will go off once your innerHTML has been loaded.

Also, take a look at the Javascript Execution Model

1
  • Thanks. But does the above either a) guarantee the image is fully loaded? At the least I'm sure it guarantees the image element is in the DOM?
    – Steve
    Aug 9, 2011 at 19:26
-2

How about creating a container div and add an onload event handler to it.

var container = document.createElement('div');
container.addEventListener('load', function() {
    // Do something here
}, false);
container.innerHTML = '<h1>Here comes my HTML</h1>';
document.getElementById('someId').appendChild(container);
2
  • 2
    does "how about" mean "seems like a good idea" or "I've tried this and know it works"? Oct 12, 2013 at 0:20
  • 1
    It works for images but not for general HTML. A possible solution could be to add a handler to all images in the HTML jsfiddle.net/b2wsc/3 Apr 29, 2014 at 10:56
-2

Have you tried to use the window.onload event? This event fires when the entire page is completely loaded including all its content like images, scripts, inner frames, etc.

P.S. If you use JQuery library, then you can use their $(window).load event wrapper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.