Javascript: Add Iframe Element After Page Has Loaded
Solution 1:
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):
<scripttype='text/javascript'>window.onload = function() {
var iframe = document.createElement('iframe');
iframe.style.display = "none";
iframe.src = /* your URL here */;
document.body.appendChild(iframe);
};
</script>
Solution 2:
If you like to load multiple iFrames after your page has loaded you can also combine it with a setTimeout()
, .ready()
and .each()
function:
Markup:
<spanclass="hidden iframe-holder"data-iframe="https://open.spotify.com/embed/track/6Js1lHzz7gu7XTyvcdLuPa"></span><iframesrc=""></iframe><spanclass="hidden iframe-holder"data-iframe="https://open.spotify.com/embed/track/4icHXsDdv3eHfa7g3WQWAP"></span><iframesrc=""></iframe><spanclass="hidden iframe-holder"data-iframe="https://open.spotify.com/embed/track/3BukJHUieqwat6hwALC23w"></span><iframesrc=""></iframe><spanclass="hidden iframe-holder"data-iframe="https://open.spotify.com/embed/track/1Pkj7fCqzg4o6ivPuWU0vB"></span><iframesrc=""></iframe>
JS (in this case jQuery - sorry I'm from the WordPress cosmos):
jQuery(document).ready(function( $ ) {
setTimeout(function(){
$(".iframe-holder").each(function(){
var iframesrces = $(this).attr('data-iframe');
var nextiFrame = $(this).next();
$(nextiFrame).attr('src',iframesrces);
});
}, 1000);
});
This solution is useful if you get your strings dynamically from a database. Just make sure that you place the iframe source holder span "before" your iframe in the DOM and it will attach its data-iframe
attribute to the iFrame element after your page has been loaded.
Post a Comment for "Javascript: Add Iframe Element After Page Has Loaded"