Recommended reading:
How to solve the slow loading of JS iFrame
In projects, it is often necessary to dynamically add iframes, and then perform related operations on the added iframes, but often the iframes have not been added yet. Well, the subsequent code has already been executed, so some of the things you wrote are not displayed at all. At this time, we have to consider whether we can wait until the iframe is loaded before performing subsequent operations. Of course, various browsers have already considered this for us, see below:
ie browser
Each elem node of IE will have an onreadystatechange event. This event is triggered every time the elem content changes. For example, loading will trigger when the content is loading, loaded will trigger when the content is loaded, and complete will trigger when the content is loaded successfully. Trigger, this function also needs to cooperate with readyState, which is an attribute owned by every elem on IE, and is used to check the status of each trigger.
//先为iframe 添加一个 onreadystatechange iframe.attachEvent("onreadystatechange", function(){ //此事件在内容没有被载入时候也会被触发,所以我们要判断状态 //有时候会比较怪异 readyState状态会跳过 complete 所以我们loaded状态也要判断 if(iframe.readyState === "complete" || iframe.readyState == "loaded"){ //代码能执行到这里说明已经载入成功完毕了 //要清除掉事件 iframe.detachEvent( "onreadystatechange", arguments.callee); //这里是回调函数 } });
Other browsers (Firefox, Opera, chrome, etc.)
In other non-IE browsers, Firefox, Opera, chrome and other iframes will have an onload event. As long as this event is triggered, The named content has been loaded.
iframe.addEventListener( "load", function(){ //代码能执行到这里说明已经载入成功完毕了 this.removeEventListener( "load", arguments.call, false); //这里是回调函数 }, false);
To summarize
if(iframe.attachEvent){ iframe.attachEvent("onreadystatechange", function() { //此事件在内容没有被载入时候也会被触发,所以我们要判断状态 //有时候会比较怪异 readyState状态会跳过 complete 所以我们loaded状态也要判断 if (iframe.readyState === "complete" || iframe.readyState == "loaded") { //代码能执行到这里说明已经载入成功完毕了 //要清除掉事件 iframe.detachEvent("onreadystatechange", arguments.callee); //这里是回调函数 } }); }else{ iframe.addEventListener("load", function() { //代码能执行到这里说明已经载入成功完毕了 this.removeEventListener("load", arguments.call, false); //这里是回调函数 }, false); }
Note: The above function must be placed in the iframe after appendChild is appended to the body, otherwise it will not be triggered
The above content is introduced by the editor. JS method to determine whether the iframe is loaded successfully, I hope it will be helpful to everyone!
For more related articles on methods to determine whether an iframe is loaded successfully based on JS (various browsers), please pay attention to the PHP Chinese website!