How to set a timeout for loading a external javasc

2019-04-05 07:23发布

问题:

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.

回答1:

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>


回答2:

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