Does body.onload wait for IFrames?

倾然丶 夕夏残阳落幕 提交于 2019-11-27 06:10:29

问题


I know that onload event waits for page resources to load before firing - images, stylesheets, etc.

But does this include IFrames inside the page? In other words, is it guaranteed that all the child Frames' onloads will always fire before the parent's does?

Also, please let me know if behavior varies between browsers.


回答1:


As I see on my pages, each iframe got independent onload, and top-frame onload doesn't wait for iframes to fire.

I got gif/png banners on my site that sometimes loads very slowly, so I put them into iframe and that made whole site and onload event to work faster.




回答2:


No, it doesn't. If you want to do something like that, you'll need to add an onload handler for the iframe. You can do this nicely with jQuery:

  <iframe src="http://digg.com"></iframe>
  <script>
    var count = $('iframe').length;
    $(function() {
      // alert('loaded'); // will show you when the regular body loads
      $('iframe').load(function() {
        count--;
        if (count == 0)
            alert('all frames loaded');
      });
    });
  </script>

This would alert when all the frames are loaded.

See the example:

http://jsbin.com/azilo




回答3:


Or plain javascript should work..

function checkIframes() {
   if(!i) { i = 0; }
   if(document.getElementsByTagName('iframe')[i]) {
      document.getElementsByTagName('iframe')[i].onload = function () { i++; checkIframes(); }
   }
   else { yourFunctionInHere(); }
}

haven't really tested this, but should work... than refer to it with document.onload = function() { checkIframes(); }

I don't really like libraries like jQuery, because so far I found I can achieve more with less code, with regular javascript.



来源:https://stackoverflow.com/questions/957133/does-body-onload-wait-for-iframes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!