简体   繁体   中英

how to know when an iframe has finished loading the DOM, but not yet all images?

My web page has an iframe, and I change its src when the user clicks on a showNewPage button. I need to know when the browser has finished loading the DOM of the iframe, but without waiting for all the images to be downloaded.

var myIFrame = document.getElementById("myIframe")
var count = 0;
funcion showNewPage() {
  myIFrame.src = "http://example.com/page_" + count;
  count++;
}

This code calls doSomething() when the iframe has finished loading the DOM and all images:

myIFrame.addEventListener("load", function(event) { doSomething(); });

How to ask myIFrame to call doSomething() when the iframe has finished loading the DOM, but not yet all the images?


ps: There is an event DOMContentLoaded instead of load which achieves this; but this event is not available for an iframe. It's available only for a document or a window. Doing as follows does not work neither, because myIFrame.contentWindow returns null at the very beginning:

myIFrame.contentWindow.addEventListener("DOMContentLoaded", function(event) { doSomething(); });

ps: this other question does not answer my question, as it relies on onload event, which waits until all images are downloaded: How to detect when an iframe has already been loaded

As you found out, trying to get its .contentWindow before the iframe has been initialized will return null .

One way around this is to

  • initialize your frame with an empty document ( about:blank ),
  • get a reference to your iframe's contentWindow , this will always be the same object, however events we attach on it will get removed at every new navigation...
  • add an unload event listener (since it's the closest to the navigation)
  • wait just a frame so our contentWindow start the navigation
  • add your DOMContentLoaded and our unload event listeners so we can reiterate at next navigation

frame.onload = e => {
  const win = frame.contentWindow;
  frame.onload = null;
  win.addEventListener( 'unload', attachEvents );
  YOUR_CALLBACK(); // make it fire even at beginning?

  function attachEvents()  {
    setTimeout( () => {
      win.addEventListener( 'DOMContentLoaded', YOUR_CALLBACK );
      win.addEventListener( 'unload', attachEvents ); // do it again at next navigation
    }, 0 );
  };
};
frame.src = "about:blank";

As a fiddle since StackSnippets over-protected iframes don't allow us to access inner frames' content...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM