dynamically created iframe triggers onload event twice

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

    To expand on the top-voted answer: if you can not control when and how things are attached to the DOM -- for instance, when using a framework (we've had this happening in our Angular app) -- you might want to try the solution below.

    I did heavy cross-browser testing and I found the following workaround: check the parameter passed to onload callback and inspect evt.target.src in the event listener.

    iframe.onload = function(evt) {
        if (evt.target.src != '') {
            // do stuff
        }
    }
    

    (if you call global method from HTML, remember to pass event in your HTML markup: