Failover loading of .js from sequence of servers?

别说谁变了你拦得住时间么 提交于 2019-12-06 04:10:14

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/7448449/failover-loading-of-js-from-sequence-of-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!