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
2 Answers
Reset to default 6If 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)