JavaScript code in iframes in IE9 not working

There is a similar way of achieving this using an existing iframe if you aren't creating a new element.

$(function () {
    var iframeSrc = $("#iframeid").attr("src"); // capture target URI
    $("#iframeid").attr("src", "about:blank"); // delay loading until we reposition in the DOM
    $("#iframeid").appendTo("#newparent").attr("src", iframeSrc); // reposition, load iframe by setting src
});

IE9 or jquery framework needs to fix this issue.


Note: here there is some documentation from IE9 that may help to understand. Thanks to @Ben Amada for sharing it.


After almost a week of going crazy day after day I found it out.

The problem with IE9 is no specifically with the javascript code in the iframes. Not even with the javascript in iframes added by javascript or any library (I have lots of js libraries and plugins that could be screwing IE9).

The problem is when you move the iframe or one ancestor through the DOM. IE9 will excecute the code in the page loaded in the iframe as many times as moves you make. Each time (but the last one) will have Object, String, Array and others undefined (and other bugs too).

Example:

var iframe = $("<iframe>").attr("src", "www.example.com").attr("id", "myIframe");
iframe.appendTo("body");
$("#myIframe").appendTo("form:eq(0)");

The javascript code in "www.example.com" will be executed once with the error described above and then once with no errors.

With the following code the code will be excecuted just once and correctly:

var iframe = $("<iframe>").attr("src", "www.example.com").attr("id", "myIframe");
iframe.appendTo("form:eq(0)");

I hope this helps someone to avoid this pain in the ass,

Diego