4

Let's imagine a web page page needing to load a javascript file (i.e. my.js). Is it possible to organize the following fail-over loading sequence?

  1. If server A is up, load my.js from server A.
  2. Else, if server B is up, load my.js from server B.
  3. Else, if server C is up, load my.js from server C.
  4. ...

If yes, how to proceed? Thanks.

P.S.: I have just found yepnopejs. Does anyone recommend it?

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • This does not sound like a programming question but a question for Active-Active Cluster environments. You may want to try ServerFault. – John Hartsock Sep 16 '11 at 17:45
  • @John no no, it is not about clustering, the servers are not necessarily part of the same cluster. – Jérôme Verstrynge Sep 16 '11 at 17:51
  • 1
    Look at [this question][1] [1]: http://stackoverflow.com/questions/5257923/how-to-load-local-script-files-as-fallback-in-cases-where-cdn-are-blocked-unavail – Infeligo Sep 16 '11 at 17:56

1 Answers1

4

I have seen this technique to allow a fallback if a CDN is down. If your js file has some testable property like a global variable (I've called it marker), you can attempt to load the file from server A, test for the marker and if it is not found script another attempt.

<script type="text/javascript" src="http://server_A.tld/my.js"></script>
<script type="text/javascript">
if( !window.marker ) {
    document.write(
        '<script type="text\/javascript" src="http:\/\/server_B.tld\/my.js"><\/script>'
    );
}
</script>

Update There is no danger that all the scripts will run using this technique. John Resig explains this in a blog post.. Scripts can download in parallel and in any order but they must execute in order.

Here is a fiddle that demonstrates

meouw
  • 41,754
  • 10
  • 52
  • 69
  • Ok, but are we sure the second statement (i.e. document write) will be executed after the attempt to load from A has failed? In other words, are we sure this is strictly sequential? (sorry if the question sounds stupid, but I am not a javascript expert) – Jérôme Verstrynge Sep 16 '11 at 18:01
  • Is it frequent that a CDN goes down? – cherouvim Sep 16 '11 at 18:47
  • @cherouvim Not very likely but not impossible I guess. – meouw Sep 16 '11 at 22:47