init fail
init fail

Reputation: 399

How to wait for iframe content to load using only javascript

I am trying to create a printing functionality for a website that dynamically loads web pages into a pop-up window. The whole situation is a little weird so I will explain what I am doing exactly and if anyone has any suggestions on how I could do this process in a more efficient way, I am all ears.

Because I have multiple web pages that need to be printed together and I cannot control what content I will be served, I decided that it would be best to load everything inside of iframes (mainly because many of the documents contain scripts and styles that would contaminate the rest if simply thrown onto a page together...)

Because iframes are not flexible, I found the only way to figure out what size my iframes need to be, I have to render each web document by itself and record the height and then render each document in an iframe with the height that I initially recorded.

So far I have gotten to the point at which I am ready to render each iframe on a single page, and am using the following code to create a new 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();

iframe is instantiated, but contentDocument appears to be null. I have tried to wait for this content to load, but it just sits and loops infinitely.

Upvotes: 1

Views: 12205

Answers (2)

gnllucena
gnllucena

Reputation: 824

You can use jQuery to wait for the frame to load, and them do your stuff.

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

EDIT: Using only javascript

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

Upvotes: 5

weisk
weisk

Reputation: 2540

you can just attach an event listener to the iframe's window:

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

Upvotes: 0

Related Questions