bobbybee
bobbybee

Reputation: 1788

Preventing an iFrame from refreshing upon adding a second iFrame

I'm developing a web-app which contains several iFrames. The frames can be added to the DOM at any point. I can successfully add the iFrame to the app currently, however, when the new iframe loads, the other iframes reload as well. In the case of a static webpage, this is fine, but in my app the iframes have widgets running, which becomes a big pain to have to manually restore their states.

Is there a way to prevent the original iframes from refreshing when the new iframe gets added in?

Original:

<iframe src="example.com" id="iframe1"></iframe>
document.getElementById("iframe1").contentWindow.whatever

After something happens:

<iframe src="example.com" id="iframe1"></iframe>
<iframe src="example.org" id="iframe2"></iframe>

iframe2 loads and iframe1 reloads

Preferred behavior:

iframe2 loads, iframe1 stays as it is until I explicitly call reload()

EDIT:

Run this on the console multiple times

document.body.innerHTML += '<iframe src="http://example.com"></iframe>';

A sample of this behavior can be seen in my window manager at

http://magnesiumbeta.com/Window.html (move the window somewhere else prior to adding a second one, to see them both refresh)

Upvotes: 1

Views: 2802

Answers (1)

ndm
ndm

Reputation: 60503

Appending DOM content this way is not supported, what you are doing there with the += operator on .innerHTML is replacing the nodes whole content with current content + new content, consequently all possible external resources are being reloaded as they are new content.

In order to avoid this you have to use the proper DOM method for appending child nodes, that is Node.appendChild()

var iframe = document.createElement('iframe');
iframe.src = 'http://example.com';
document.body.appendChild(iframe);

or since you are already using jQuery, use its own append() method.

$(document.body).append('<iframe src="http://example.com"></iframe>');

Upvotes: 2

Related Questions