如何设置加载已关闭的外部 javascript 文件的超时时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5506425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:25:51  来源:igfitidea点击:

How to set a timeout for loading a external javascript file which is down

javascriptajaxtimeout

提问by Vish

Im 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.

我使用 javascript 来包含从另一台服务器上的 php 文件提供的一些内容。然而,这个其他服务有时会变得不稳定,要么需要很长时间才能加载,要么根本不会加载。

Is there a way in JS to try to get the external data for x number of seconds before failing and stopping to include js.

JS 中有没有办法在失败并停止包含 js 之前尝试获取 x 秒的外部数据。

采纳答案by mplungjan

If you mean

如果你的意思是

<script src="javascript.php"></script>

then the short answer is no which is why JSONP is not useful in these cases.

那么简短的回答是否定的,这就是 JSONP 在这些情况下没有用的原因。

The longer answer is that you might be able to use setTimeout and test a variable you KNOW should be in the javascript and give an error if the var/function is not there.

更长的答案是,您可能能够使用 setTimeout 并测试您知道应该在 javascript 中的变量,并在 var/function 不存在时给出错误。

If you do

如果你这样做

<script>
var start = new Date();
var tId;
function testFunction() {
  var end = new Date();
  if ( (end.getTime()-start.getTime()) > 10000) {
    alert('gave up')
  }
  else if (someFunction) { // someFuntion in the external JS
    someFunction()
  }
  else tId=setTimeout(testFunction,1000)
}
</script>

<script src="javascript.php"></script>

回答by beausoleilm

<script type="text/javascript">
var jsLoaded = false;
setTimeout("callback()", 2000);
function callback() {
    if (!jsLoaded) {
        alert("Javascript not loaded after 2 seconds!");
    } else {
        alert('Loaded');
    }
}
</script>
<script type="text/javascript" id="foo" src="url.js" onload="jsLoaded=true"></script>

Now, good luck to find what to do in order to stop loading the script.. I've tried to remove the <script>element from the DOM but it's still try to load...

现在,运气好能找到什么,以便阻止加载脚本做..我试图删除<script>从DOM元素,但它仍然尝试加载...

If you .js is hosted on the same domain, I suggest you to use AJAX method to load the javascript (see http://codesnippets.joyent.com/posts/show/602)

如果您的 .js 托管在同一域中,我建议您使用 AJAX 方法加载 javascript(请参阅http://codesnippets.joyent.com/posts/show/602