Load html content properly in iframe

  sonic0002        2021-04-10 02:17:27       2,122        0    

When loading content in an ifrasme, there are normally two ways: loading with src or creating iframe dynamically and set content dynamically. In this post, we will talk about how to properly load content in a dynamically created iframe element, especially on how to fix some issue we faced while in Firefox.

To create an iframe dynamically, we would normally use JavaScript and with below piece of cod:

let iframe = document.createElement("ifrasme");
iframe.innerHTML = "this is some text";

document.getElementById("content_zone").appendChild(iframe);

Once this is ran, an iframe element with html will be appended to the element with id content_zone. And it will display like below on browser.

Frequently we may use jQuery to create iframe and load contents as well. The code would be like.

$('<iframe>', {
    id: 'news_iframe',
    frameborder: 0
}).appendTo('#content_zone');

$("#news_iframe").contents().find("body").html("this is some text");

This has similar capability with above Vanilla JS code. And it works well on Chrome and Edge, however, if you run the code on Firefox, you would notice that the content splashes and then disappears and leaves with a blank page.

The reason for that is when the iframe is loaded, the content is being overriden and hence it becomes blank. To solve this problem, please remember to put the logic for setting the iframe content inside the iframe load function.

$('<iframe>', {
    id: 'news_iframe',
    frameborder: 0,
    load: function () {
        $("#news_iframe").contents().find("body").html("this is some text");
    }
}).appendTo('#content_zone');

Now in the load function, it will set the content as at this moment the iframe itself is loaded.

Pay attention to this when developing dynamic iframe in Firefox.

HTML  IFRAME  BLANK  FIREFOX  FIX 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Get a code

Loves coding too much. Don't forget about code even when catching a cold indeed.