Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 551
Vish Avatar asked Mar 31 '11 21:03

Vish


1 Answers

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>
like image 176
mplungjan Avatar answered Oct 17 '22 00:10

mplungjan