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

前端 未结 4 848
余生分开走
余生分开走 2020-12-17 18:15

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 t

4条回答
  •  佛祖请我去吃肉
    2020-12-17 18:47

    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

提交回复
热议问题