skip to Main Content

In the context of a javascript + html + css dynamic web page, is there a way to detect the completion of the page update (including the load of images) as a result of a DOM change?

NOTE: I’m not lookgin for the events like "load", "DOMContentLoaded", "readystatechange", as these are only triggered during the page load, which is not relevant for my scenario.

Thanks

document.addEventListener("<some event>", function(event) {
    console.log('==Updated====');
}, false);

2

Answers


  1. For general page updates you could use MutationObserver:

    const observer = new MutationObserver(() => {
      console.log("DOM updated");
    });
    
    observer.observe(document.documentElement, {
      childList: true, // adding or removing nodes
      characterData: true, // text changes
      attributes: true, // attribute changes
      subtree: true // descendant nodes
    });
    

    Observing DOM updates this way can be expensive, so make sure to only use options that you need. Also the callback passed to MutationObserver should be performant because it gets executed frequently.

    For loading images, there is a load event which fires when the image has been loaded. Something like this would work:

    const image = new Image();
    image.onload = () => {
      console.log("image loaded");
    };
    image.src = "https://example.test/1.jpg";
    

    Please note that load event doesn’t buble, so you would need to add event listeners to individual images.

    Login or Signup to reply.
  2. I have not worked this approach, I’m just letting you know based what I have explored. There is a API called MutationObserver please refer the documentation of the MutationObserver link to the documentation This may help with your requirement. also please check somebody has a similar question as yours. link to the question

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search