13

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.

Vish
  • 4,508
  • 10
  • 42
  • 74

2 Answers2

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
5
<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)

beausoleilm
  • 71
  • 1
  • 1
  • `setTimeout("callback()", 2000);` ???? I think you mean `setTimeout(callback, 2000);` .. other than that it should work (I did a very different version that does work using the same principles). – www-0av-Com Mar 10 '18 at 18:10
  • Both work as you can read on the best answer here: https://stackoverflow.com/questions/6081560/is-there-ever-a-good-reason-to-pass-a-string-to-settimeout In any case I was sharing an idea more than a ready-to-use code. Feel free to change it :) good job! – beausoleilm Mar 11 '18 at 13:13
  • Fair dos. By the way, I marked you up as I agree the idea is sound. I don't know who originally marked you down (without comment), but at least you are now back at zero. – www-0av-Com Mar 16 '18 at 16:39