Learning event listeners when an iframe (c) of listening window iframe has finished loading

Foreword

Often we encounter such a situation.

When embedded in another page in the iframe. If the iframe load pages faster response, maybe we do not feel out of sync page load, but imagine, in response iframe page if need be embedded into a very slow, there will be What kind of phenomenon? Then there will be all the page has finished loading, but

At iframe element, there will be blank until the embedded page has loaded, this space will display the newly loaded page. One can imagine that a blank page if prolonged, for the viewer, it will mean anything. If embedded in the page is not finished loading, to give a loaded message. Such as: "the page loads

In "like, I think this page to browse users, it will no longer be suffering, but also to enjoy a visual.

To achieve this effect, generally follows the principle of processing.

  • iframe load area gives friendly message.

  • When the iframe has finished loading, clear message, and let the iframe display.

These are relatively easy, but the key question now is how to listen pages within the iframe element is already loaded.

The key to this problem, in general, will be divided into two cases to discuss solutions.

  • Sympatric nesting: It is best to let the child call the parent page page method.

  • Exotic nesting: If it is exotic, but sub-pages can not be modified, then: In Firefox / Opera / Safari, you can use iframe onload event directly; but in IE, document.readyState sub-pages can be determined by a timer, or use in response to the events of the iframe onreadystatechange event calculations.

It contains a simple iframe parent page will look like the following:

<!DOCTYPE ...>
<html xmlns="...">
  <head>
  <meta ... />
  <title>Iframe</title>
  <body>
    <iframe name="iframe1"  id="iframe1" width="300" height="50" src="#" ></iframe>
    <script type="text/javascript">//codes here</script>
  </body>
</html>

Start:

A, with nested domains

Call the parent page object

parent.html

function ifrmLoaded() {
    // code here
}
sub.html

window.onload = function() {
    window.parent.ifrmLoaded();
}

Disadvantages:

  • Child parent page must be in the same domain

  • Pair needs to have the right to modify the page; or, you can ask a colleague responsible for this piece of code to add sub-pages for us
<script type=”text/javascript”>
  if(window.parent!=window) window.parent.iframeCall();
</script>

Window.onlad put it in, or directly on the </ body> before.

Notes [1]: a front end programming iframe window or other properties in the same domain is the perfect congenital conditions. As long as the same domain name, the object is shared between each window, and we are fully free to play, ride back and forth between different windows. In short, only think, not impossible.

Sometimes, in order to prevent their pages are not nested others, the following can be used to resolve:

if(window.parent!=window) window.parent.location="http://hqlong.com";
//or
if(window.top!=window) window.top.location="http://hqlong.com";

Second, the exotic nested (or sub-page already exists and can not be modified)

In the pages of different domain names, browsers for security reasons, almost completely blocked the objects between pages and from

In a nested page in the exotic, sub-pages you can always change the direct location of the parent window to prevent nesting, but the parent page of this can not help it. Of course, in addition to sub-pages just eternally have the right to modify the parent window .location the outside, nor the other. For example, in the IEs, can directly modify subpage parent page

The .location another source:

<script tyle=”text/javascript”>parent.location=”http://anotherPage.com/”;</script>

But can not access other objects, such as sub-attributes window.name, document, etc., etc. even location.href location will not be able to access. Of course, in terms of preventing nesting, use top.location will be more powerful.

Method a: use to determine onreadystatechange

[Firefox / Opera / Safari directly using iframe onload event]

document.getElementById('ifrm').onload = function() {
    //here doc
}

[In IE, registered iframe onreadystatechange event]

iframe onreadystatechange incident

var oFrm = document.getElementById('ifrm');
oFrm.onreadystatechange = function() {
    if (this.readyState &amp;&amp; this.readyState == 'complete') {
        onComplete();
    }
}

Timer test document.readyState 

var oFrm = document.getElementById('ifrm');
var fmState=function(){
    was state = null;
    if(document.readyState){
        try{
            state=oFrm.document.readyState;
        }catch(e){state=null;}
        if(state=="complete" || !state) {
            onComplete();
            return;
        }
        window.setTimeout(fmState,10);
    }
};
// When changing the src or submit a form by form target, execute the statement: 
IF (fmState.TimeoutInt) window.clearTimeout (fmState.timeoutInt);
fmState.timeoutInt = window.setTimeout(fmState,400);

Each time the page is loaded iframe will be activated in the process onreadystatechange event three times, the corresponding state are loading, interactive and complete, and the last is complete.

The question: Why should a delay of 400 milliseconds?

Because javascript DOM operation is asynchronous, we must wait for the script to execute after the DOM implementation to start the next step. 400 seconds This number depends on the speed of response and the client device and browser, the response speed of the device can be good even faster in less than 10 milliseconds, but may be more popular around 100 ms, 400 ms should be a very conservative. In short, a large number of milliseconds can fit more user equipment status, and reduce the workload of the client device. As document.readyState, referring docuent.readyState iframe within a sub-page, rather than the parent page

Question two: Why try and catch?

Because in the case of exotic, sub-page when the iframe to reach the interactive state, will lose access to the parent page, it can only return to this step is loaded, so IE an unknown error - in fact, no authority, so try and catch, let the error go silent.

[ Compatible handling Firefox / Opera / Safari / IE's ]

var oFrm = document.getElementById('ifrm');
oFrm.onload = oFrm.onreadystatechange = function() {
     if (this.readyState && this.readyState != 'complete') return;
     else {
         onComplete();
     }
}

or

var $iFrame=$("#IFrame");
$iFrame.prop("src","http://www.baidu.com");
IF (! / * @ @ aijquery * / 0 ) {  // If not IE, IE conditions Notes   
    $ iFrame [0] .onload = function      () {
        alert ( "loaded" ); 
    };  
}else{  
    iFrame and $ [0] .onready stateChange = function () {  //  node in the event onreadystatechange have IE   
         if (iframe.readyState == "complete")   {
            alert ( "loaded" ); 
        }  
    };  
}

Option two: Analyzing attachEvent

var $iFrame=$("#IFrame");
$iFrame.prop("src","http://www.360.cn");
IF ($ iFrame and [0 ] .attachEvent) {  
       $ iFrame and [0] .attachEvent ( "the onload", F Unction () {  //  IEs   
              Alert ( "loaded" ); 
      });  
}  The else  {   
      $ iFrame and [ 0 ] .onload = function () {  //  non IEs   
              Alert ( "loaded" );  
      };  
}

Method 3: Use the load is determined in jquery

var $iFrame=$("#IFrame");      
$iFrame.prop("src","http://www.aijquery.cn");    
$iFrame.load(function(){       
    alert ( "loaded");    
});

note

Use the above case method you must be dynamically created iframe or dynamically added iframe src specified address

reference

Event listeners when the iframe load is complete

jquery iFrame is judged whether the three ways of frame loaded

Cross-browser iframe onload event listener

Guess you like

Origin www.cnblogs.com/kunmomo/p/12126403.html