开发者

Load an iframe asynchronously

I have a webpage with an <iframe> pointing to anoth开发者_如何学运维er website. I don't want this to block the loading of the rest of the page. Is there a way to load it asyncrounously?


It shouldn't block. If you want the main page to fully load first (eg, main page's images before iframe content) then you'll have to use a bit of javascript to set the url of the iframe, like <body onload="javascript:...">


Using jQuery, this works:

<script type="text/javascript">
  $(window).load(function() {
    var f = document.createElement('iframe');
    f.src = url; 
    f.width = 1000; 
    f.height = 500;
    $('body').append(f);
  });
</script>

where url is some URL.


One problem we had was that while iframes already do load asynchronously, the main page will not fire OnLoad until the iframe has finished loading too.

We worked around this by 'faking' OnLoad by calling the method we wanted in a script element at the bottom of the main page, even outside the closing body tag:

</body>
<script  type='text/jscript' language='javascript'>
BodyOnready();
</script>


I think @Coxy is correct that the OnLoad won't fire. At least when running some web page performance tests it seemed to me it is waiting for the iframe to consider the page to be fully loaded. I therefore use this small jQuery snippet to load the iframe:

HTML: <iframe id="blabla"></iframe>

JS:

$(window).load(function() {
   if ($('#blabla').length <= 0) { return; }  // to avoid errors in case the element doesn't exist on the page / removed.
   $('#blabla').attr('src','//example.com/page');
});


iframes should load asynchronously without any effort on your part.


you can wait until after 'onload' has fired to set the iframe's src:

<body onload="loadFrame">

then something like this:

function loadFrame(){
    var myFrame = document.getElementById('myFrame');
    myFrame.src = "myURL";
};


Some vanilla JS alternative:

HTML:

<iframe id="YOURID" src="about:blank">Loading...</iframe>

JS:

window.onload = function(){
  document.getElementById('YOURID').src = 'https://insertYourUrlHere.com'
};


Although I agree this shouldn't be happening, you could wait for your webpage to be completely loaded, and then load the iframe contents. With jQuery, I think you can do something like this:

  • Supposing your IFRAME looks like: <iframe name="theOtherPage"></iframe>


$(document).ready(function(){
  (window.frames || document.frames)["theOtherPage"].window.location = "http://theotherpage.com/"; 
});

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜