简体   繁体   中英

Determine when iFrame content is rendered after IFrame has already loaded

Using javascript I'm creating an iframe, adding it to the parent DOM and then writing HTML to it via iFrameEl.contentWindow.document.write()

I need to determine when all content in the iFrame has been rendered after iFrameEl.contentWindow.document.closed() has been called.

The iFrame's onload event appears to be called when the iframe is added to the DOM originally, before I can write to it and I need to add it to the DOM in order to get access to the iFrame's contentWindow.document, so catch 22.

In Chrome, as an alternative I have used the srcdoc attribute to add all the content I need to the iframe and the add the iframe to the dom and wait for the onload event however srcdoc is not supported in IE

    var iFrameHTML = '<!DOCTYPE html><html><head>';

    iFrameHTML = iFrameHTML + '</head><body>' + htmlIncludingImagesEtc + '</body></html>';

    iFrameEl.srcdoc = iFrameHTML;

    myDiv.append(iFrame);


    iFrameEl.onload = function(){ 

        //proceed
    }

I know the iFrame's src attribute can also be used, but the limitation on Data URI characters prevents me from using that approach

I know there are many similar questions on here, but I could not find any that matches my requirements.

I need to dynamically create an iFrame, add content to it and determine when all the content has been rendered, is there some obvious way to achieve this, or will it require MutationObservers etc.?

Check out DOMFrameContentLoaded . It is an event that will be fired when the content in the frame is loaded and parsed.

Late answer, but it may help someone...I found that even after the iframe was added to the DOM, if I added the links to style sheets from the head of the parent DOM to the iframe as a String as follows, it meant that the load event occurred

iFrame$.on('load',function(){
//iFrame loaded
});

var headHTML = '<head>';
$('head link').each(function(index, link) {
headHTML = headHTML + link.outerHTML;
});

headHTML = headHTML + '</head>';

iFrameDoc.open();
iFrameDoc.write("<!DOCTYPE html>");
iFrameDoc.write("<html>");
iFrameDoc.write(headHTML);
iFrameDoc.write("</body>");
iFrameDoc.write("</html>");
iFrameDoc.close();

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