如何设置超时以加载已关闭的外部javascript文件 [英] How to set a timeout for loading a external javascript file which is down
问题描述
我正在使用javascript来包含从另一台服务器上的php文件提供的某些内容.但是,其他服务有时会变得不稳定,或者加载时间长或根本无法加载.
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.
在JS中,有一种方法可以尝试在x秒内获取外部数据,然后失败并停止包含js.
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.
推荐答案
如果您的意思是
<script src="javascript.php"></script>
然后简短的回答是否",这就是为什么JSONP在这些情况下没有用的原因.
then the short answer is no which is why JSONP is not useful in these cases.
更长的答案是,您可能可以使用setTimeout并测试您应该在javascript中知道的变量,如果var/function不存在,则会给出错误消息.
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.
如果愿意
<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>
这篇关于如何设置超时以加载已关闭的外部javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!