undefinedfix
Sign in

How can I listen to the completion of loading for dynamically added iframes?

0x30c4 edited in Thu, 08 Dec 2022

Iframe is added dynamically, and then the picture is inserted into the iframe to call printing. However, the first time printing is executed, it is blank, and the picture has not been loaded. I added the onload event of iframe, but it will not be executed. How should I judge that all the elements in the iframe have been loaded?

var img = new Image();
img.src = '.....';
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.contentDocument.body.onload = function(){
    console.log('加载完成');
}
iframe.contentDocument.body.appendChild(img);
1 Replies
jet_black82
commented on Thu, 08 Dec 2022

------Update - I see your code onload is still bound to iframe.contentDocument.body On the other hand, you should be able to correctly execute the callback in two places:

  1. Onload is bound to iframe
  2. The onload binding code is written in document.body.appendChild Before (iframe), if the iframe is inserted first, the iframe may have been loaded and the subsequent events will be bound, so the callback will not be executed

As for the second point above, I have tested that if the iframe SRC attribute is added with a real link, the loading will not be completed quickly, so the onload can be executed normally even if it is inserted first and then bound. However, if iframe does not have SRC attribute, it will be loaded quickly, and event binding will be invalid if it is placed later. The loading of the iframe page is uncontrollable, so it's safe to write the onload binding code in the document.body.appendChild (iframe).

-------The original answer - I tried you this code should report an error. The iframe cannot be accessed before it is inserted into the page iframe.contentDocument.body Yes. Moreover, the onload event should not be bound to the body, but to the iframe.

var img = new Image();
img.src = '.....';
var iframe = document.createElement('iframe');
iframe.onload = function(){
    iframe.contentDocument.body.appendChild(img);
    console.log('加载完成');
}