Waiting for iframe content to load with JavaScript: A Guide

Feedback

Question:

My aim is to develop a
printing functionality
that enables dynamic loading of web pages in a pop-up window on a website. As the process is a bit peculiar, let me elaborate on it, and I am open to any recommendations on how to make it more effective.

To ensure that multiple web pages are printed together without any unwanted content, I have chosen to use iframes. This is because several documents include scripts and styles that can contaminate the rest of the content if added directly to the page.

As iframes lack flexibility, determining their size requires rendering each web document separately and recording its height. Afterwards, the document can be rendered in an iframe with the initially recorded height.

At this point, I am prepared to display every iframe on one page. To accomplish this, I am utilizing a code that generates a fresh
iframe element
.

var body = popWindow.document.createElement("body");
var iframe = popWindow.document.createElement("iframe");
iframe.contentDocument.open();
iframe.contentDocument.write(data);
iframe.contentDocument.close();

The issue happens when I hit

iframe.contentDocument.open();

The iframe has been created, however, contentDocument seems to be absent. Despite my attempts to wait for the content to load, it remains stuck in an infinite loop.


Solution 1:

Utilizing jQuery, you can pause execution until the frame has loaded and then proceed with your desired actions.

$("#your-frame").load(function () {
    //frames["your-frame"]
});

EDIT: Using only javascript

var yourFrame = document.getElementById('your-frame'); 
    yourFrame.addEventListener("load", function() { 
});


Solution 2:


You only need to add an event listener to the window of the iframe.

iframe.window.addEventListener('load', function(){ ...

Frequently Asked Questions