dynamically created iframe triggers onload event twice

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

    I've also encountered the same problem, but get no answer anywhere, so I tested by myself.

    The iframe onload event will be triggered twice in webkit browsers ( safari/chrome ), if you attach the onload event BEFORE the iframe is appended to the body.

    So you can prevent iframe onload twice by change your codes in the following way.

    document.body.appendChild(ifr);
    ifr.onload=frameOnload; // attach onload event after the iframe is added to the body
    

    Then, you will only get one onload event, which is the event the document really loaded.

提交回复
热议问题