Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: add iframe element after page has loaded

Tags:

javascript

Using Javascript I need to find the best way to add a iframe element that is:

  1. Completely hidden from the user.
  2. Created after the page has fully loaded. i.e. Should be completely unobtrusive to the user and not affect loading of images and other scripts etc, in any way.
like image 231
EddyR Avatar asked Jun 18 '10 13:06

EddyR


People also ask

How do you call a function after an iframe is loaded?

To call a JavaScript function when iframe finished loading, we can add an event listener for the load event. to add an iframe. to select the iframe with querySelector .

What is onload iframe?

log("iframe content loaded"); } ); } JavaScript executes the window. onload function once it loads all the elements of the window . The addEventListener() function of JavaScript links a event listener to the HTML object.

Can iframe load JavaScript?

To capture iframe load complete event with JavaScript, we can set the onload property of the iframe to a function that runs when the iframe content finishes loading. const iframe = document.


1 Answers

You can add a hidden iframe like this:

var iframe = document.createElement('iframe'); iframe.style.display = "none"; iframe.src = /* your URL here */; document.body.appendChild(iframe); 

If you need to do that on page load, you can simply put the relevant code in a script tag at the end of your document, or hook it up via window load event (window.onload = yourFunction;), although the window load event happens quite late in the page load process. And of course, like many things involving JavaScript on browsers, you may find your life is a bit easier if you use a library like Prototype, jQuery, Closure, or any of several others, as these can smooth out browser differences. (That said, the above code will work on any browser I'm familiar with.) Libraries will typically offer a way of doing things as soon as the page is loaded, but earlier than window load typically happens. jQuery provides the ready function; Prototype provides the dom:loaded event; etc.

For instance, if you put this at the end of your body tag, it will create the iframe after everything else has loaded (including all images, window load doesn't fire until all images have loaded):

<script type='text/javascript'> window.onload = function() {     var iframe = document.createElement('iframe');     iframe.style.display = "none";     iframe.src = /* your URL here */;     document.body.appendChild(iframe); }; </script> 
like image 51
T.J. Crowder Avatar answered Sep 29 '22 17:09

T.J. Crowder