JavaScript: set a timeout for blocking scripts

JavaScript: set a timeout for blocking scripts

How to set a timeout when fetching remote scripts.

Every web browser has its way to handle the download of remote resources. Sadly, there's no way on the client-side to set an explicit timeout when dealing with remote scripts which take too long to be fetched and executed. This is the case of social network widgets.

Consider the following snippet:


<a class="twitter-timeline" href="https://twitter.com/gabromanato" data-widget-id="297349158094901248">Tweets by @gabromanato</a>
<script>
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>

This is a simple Twitter timeline. Usually this kind of script is inserted within the body of an HTML document. A browser must fetch the script located at http://platform.twitter.com/widgets.js and execute its code.

If the remote resource takes too long to be fetched, our page won't finish the loading process. A blank space will appear instead of the widget's contents and the rest of the page contents will be displayed only when the browser triggers a timeout for the blocking remote script.

As stated above, there's no way to set a timeout on the client's side. We have to proceed on the server side:


$ch = curl_init();
$timeout = 5;
$url = 'http://platform.twitter.com/widgets.js';

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);

$data = curl_exec($ch);

if(curl_errno($ch) == 'CURLE_OPERATION_TIMEDOUT' ) {
	// timeout: display alternate content
} else {
	// display the widget
}

curl_close($ch);

Assuming that you've specified the correct URL, you can extend your preliminary check to encompass other HTTP errors. Read the official documentation for further details.