dynamically created iframe triggers onload event twice

前端 未结 6 1879
鱼传尺愫
鱼传尺愫 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:38

    FWIW, while I was able to reproduce double onload in case where iframe.src is javascript:, I was not able to reproduce it with a normal HTTP URL (onload was happening once). However, when you change the order of calls so that iframe.src is set after appending to body, then the double-load happens (again, webkit only):

    var i = 0;
    
    var iframe = document.createElement("iframe");
    iframe.onload = function(){
      console.log("frameOnload", ++i);
    };
    document.body.appendChild(iframe);
    iframe.src = "http://www.example.org/";
    //iframe.src = "http://www.example.org/404";
    
    // double onload!
    

    When I assign src before appending, I get one onload call.

    var i = 0;
    
    var iframe = document.createElement("iframe");
    iframe.onload = function(){
      console.log("frameOnload", ++i);
    };
    iframe.src = "http://www.example.org/";
    //iframe.src = "http://www.example.org/404";
    document.body.appendChild(iframe);
    
    // only one onload
    

提交回复
热议问题