anon
anon

Reputation:

Load a Javascript file, but cancel if it takes too long?

Anyone have a good way to load a JS file but cancel loading it if it takes too long?

I'm thinking something like this, hypothetically:

<script type="text/javascript" cancel_after="2000" src="myfile.js"></script>

The script is code that needs to get loaded in the head, because it replaces elements on the page, and so the browser needs to block while loading it. But in case the server takes too long to respond, I'd like to be able to have the browser proceed without loading the script.

Upvotes: 0

Views: 2062

Answers (3)

Zirak
Zirak

Reputation: 39808

Use a preloader. I personally prefer yepnope, where you can easily set a timeout using yepnope.errorTimeout = 2000

Check the linked page for a rather complete documentation of yepnope.

Upvotes: 3

RobertO
RobertO

Reputation: 2663

You can put <script></script> after <body></body> or load it via JS (document.onload)

If you really want to cancel loading, then think about using XMLHTTPRequest and abort() function

Upvotes: 1

Allain Lalonde
Allain Lalonde

Reputation: 93348

You can load the JavaScript using an ajax call then use eval to run it at your leisure. In jQuery it would look something like this.

$.ajax('test.js', {timeout: 100 /* milliseconds */, success: function(result) {
  eval(result);
});

It aint pretty, and the code in the included JavaScript may need to be coded differently, but this might do it for you.

Upvotes: 1

Related Questions