dynamically created iframe triggers onload event twice

前端 未结 6 1885
鱼传尺愫
鱼传尺愫 2020-12-14 06:50

I created an iframe dynamically and found that this iframe trigger onload event twice.

var i=0;
frameOnload=function(){
  console.log(i++);  
};

var ifr=doc         


        
6条回答
  •  长情又很酷
    2020-12-14 07:21

    Building on @jakub.g's answer:

    From inside the frame, the evt.target.src hack does not work. But I found that I could instead check the evt.target.title. The second time DOMContentLoaded is triggered, evt.target points to the document being loaded, so this would work:

    document.addEventListener('DOMContentLoaded', function(evt) {
      if (evt.target.title !== myPageTitle) {
        // Work around for Webkit browsers trigging this event twice om iframes
        return
      }
      // DOM content loaded, for real
    }
    

    This behavior seems to be consistent even in Internet Explorer (save for old versions without .addEventListener

提交回复
热议问题