Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

html - Any way to gracefully enforce a timeout limit when loading a slow external file via javascript?

I'm using javascript to include some content served up from a php file on another server. However, this other service can sometimes get flaky and either take a long time to load or will not load at all.

Is there a way in JS to try to get the external data for x number of seconds before failing and displaying a "please try again" message?

<script type="text/javascript" src="htp://otherserver.com/myscript.php"></script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Couple issues: you can use timeout thresholds with XMLHttpRequest (aka ajax), but then since it's on an otherserver.com you cannot use XMLHttpRequest (and support all A-grade browsers) due to the Same Origin Policy restriction.

If the script introduces any kind of global name (eg any variable name, function name, etc) You can try setTimeout to keep checking for it:

var TIMELIMIT = 5; // seconds until timeout
var start = new Date;

setTimeout(function() {
  // check for something introduced by your external script.
  // A variable, namespace or function name here is adequate:
  var scriptIncluded = 'otherServerVariable' in window;

  if(!scriptIncluded) {
    if ((new Date - start) / 1000 >= TIMELIMIT) {
      // timed out
      alert("Please try again")
    }
    else {
      // keep waiting...
      setTimeout(arguments.callee, 100)
    }
  }
}, 100)

The problem as I see it is you cannot cancel the request for the script. Please someone correct me if I'm wrong but removing the <script> from the DOM will still leave the browser's request for the resource active. So although you can detect that the script is taking longer than x seconds to load, you can't cancel the request.

I think you may be out of luck.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...