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);
------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:
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('加载完成');
}