任何方式加载通过JavaScript较慢的外部文件时,正常执行超时限制?较慢、加载、正常、方式

2023-09-10 13:42:21 作者:爱了、倦了、淡了、散了

我使用javascript,包括一些内容提供了从另一台服务器上的PHP文件。然而,这等服务有时可以得到片状,要么需要很长的时间来加载或不会加载。

有没有办法在JS尝试失败,并显示请重试消息之前获取外部数据的秒×多少?

 <脚本类型=文/ JavaScript的SRC =HTP://otherserver.com/myscript.php>< / SCRIPT>
 

解决方案

夫妇的问题:你可以使用超时阈​​值与 XMLHtt prequest (又名阿贾克斯),但然后,因为它是在一个 otherserver.com 则不能使用 XMLHtt prequest (支持所有A级浏览器)由于同源策略限制。

如果脚本引入任何一种全局名称(如任何变量名,函数名等),你可以尝试的setTimeout 来继续检查它:

  VAR时限= 5; //秒钟,直到超时
VAR开始=新的日期;

的setTimeout(函数(){
  //检查的东西被你的外部脚本介绍。
  //变量,命名空间或函数的名字在这里是充分的:
  VAR scriptIncluded ='otherServerVariable'窗口;

  如果(!scriptIncluded){
    如果((新的日期 - 启动)/ 1000> =时限){
      // 时间到
      警报(请重试)
    }
    其他 {
      // 继续等待...
      的setTimeout(arguments.callee的,100)
    }
  }
},100)
 
使用 SpreadJS 实现 JavaScript 中导入和导出 Excel 文件

在我看来问题是你无法取消的脚本的请求。请有人纠正我,如果我错了,但删除<脚本> 从DOM仍然会留下的资源激活浏览器的请求。因此,尽管你可以的检测的脚本的时间比x秒更长的时间来加载,你不能的取消的要求。

我想你可能是出于运气。

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>

解决方案

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.