最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ajax - How to set a timeout for loading a external javascript file which is down - Stack Overflow

programmeradmin2浏览0评论

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.

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.

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.

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.

Share Improve this question asked Mar 31, 2011 at 21:14 VishVish 4,49210 gold badges45 silver badges76 bronze badges 3
  • Possible duplicate of stackoverflow.com/questions/1018705/… – Ender Commented Mar 31, 2011 at 21:15
  • Possibly not. I think this is a JSONP-type question – mplungjan Commented Mar 31, 2011 at 21:23
  • you want the request to wait N seconds, or to make N tries for the resource? – Pablo Fernandez Commented Mar 31, 2011 at 21:28
Add a comment  | 

2 Answers 2

Reset to default 6

If you mean

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

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

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.

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

If your .js is hosted on the same domain, I suggest you to use AJAX method to load the javascript (see Load external file into div)

发布评论

评论列表(0)

  1. 暂无评论