I’m writing a JavaScript widget, which is intended for use on other website and loads additional script files from my own web site (which basically means no XHR due to cross-domain limitations). Now I want to handle failures gracefully – if one script fails to load, I want to load the script from an alternate server.
I managed to handle server failures where the 1st server returns an error, but I also want to handle a timeout – if the 1st server takes too long to respond I want to abort the load and switch to the alternate.
The problem I have is that I can setup a timeout to trigger a method that switches to the alternate server, but the script from the alternate server doesn’t load successfully until the browser itself times-out on the original request – which is way too long for my needs.
I want to be able to – while the 1st <script> tag is loading – abort the load, and add a second <script> tag that points to the alternate server.
I’ve tried setting the original script’s src attribute to null, and even removing the tag from the HEAD element using removeNode(), but to no effect.
This all was tried on Firefox – I haven’t tried IE yet, but the solution has to work on both. I’d love to hear any suggestions.
Unfortunately it’s not possible to cancel the request for tags. Historically browsers only allow 2 requests at the same time to one hostname, so it should be possible to load the second script from another server.
Do you initiate the script loading before body.onload? For a normal page load the browser waits for each script to load before continuing since the scripts can alter the document. If the script is not modifying the document, you can use the defer attribute so the browser continues to render the document while your script loads.
jQuery has a few open requests on a similar feature: http://dev.jquery.com/ticket/1863 http://dev.jquery.com/ticket/3442