iframe loading time limit use javascript

2019-06-14 04:59发布

问题:

i need to stop loading my iframe page after 5000 ms i'm use these but it's refresh the iframe every 5000 ms later what the problem . pleas fix it pleas. thanks

<iframe id="iframe1" src="" width="920" height="900" border="2"></iframe>
<script type="text/javascript"> 
function setIframeSrc() {
  var s = "http://lx5.in/CGIT-Results-p2-2013.php";
  var iframe1 = document.getElementById('iframe1');
  if ( -1 == navigator.userAgent.indexOf("MSIE") ) {
    iframe1.src = s;
setTimeout(setIframeSrc, 5000);
  }
  else {
    iframe1.location = s;
setTimeout(setIframeSrc, 5000);
  }
}
setTimeout(setIframeSrc, 5000);
</script>

回答1:

To stop iframe loading you can use the following code based on this answer:

function setIframeSrc() {
  var s = "http://lx5.in/CGIT-Results-p2-2013.php";
  var iframe1 = document.getElementById('iframe1');
  iframe1.src = s;
  setTimeout(function(){
      if (window.stop) {
          window.stop();
      } else {
          document.execCommand('Stop'); // MSIE
      }
  }, 5000);
}
setTimeout(setIframeSrc, 5000);

jsfiddle / jsfiddle/show



回答2:

I would suggest rethinking the idea. IMO it should be the server that displays timeout information and not the client using some JavaScript timeouts. Explanation below.

Your code just says: refresh the iframe every 5 seconds.

You cannot stop iframe request execution. You can change iframe's src location or remove it from the DOM tree. But the request that is started is unstoppable once it reaches the server.

So:

<iframe id="iframe1" src="{url to query}" ...>

and in the script:

function displayTimeout() {
 (...)
 var p = iframe1.parentNode;
 p.removeChild(iframe1);
 var div = document.createElement("div");
 var text = document.createTextNode("Timeout loading iframe");
 div.appendChild(text);
 p.appendChild(div);
}
setTimeout(displayTimeout,5000);

But this solution has serious drawbacks - in order not to display timeout when iframe manages to load in time you should cancel the timeout. But how to do that?

If you want to do it from iframe - see iframe accessing parent DOM?

If from parent element - see jQuery/JavaScript: accessing contents of an iframe

The further you go, the more problems and the more complicated the solution becomes. So I would suggest abandoning it.