简体   繁体   English

有没有办法尝试在 HTML/JavaScript 中加载文件并在未加载时进行后备?

[英]Is there a way to try and load a file in HTML/JavaScript and have a fallback if it doesn't load?

I just switched to start using a CDN for external images/static files for my site and I wanted to know how I could build a backup in case this CDN failed.我刚刚切换到开始为我的站点使用 CDN 来存储外部图像/静态文件,我想知道如何构建备份以防这个 CDN 失败。 Is there a way to reference an external link in an HTML/JavaScript file that would let you specify a fallback location for that file if it is unavailable in the first external host?有没有办法引用 HTML/JavaScript 文件中的外部链接,如果该文件在第一个外部主机中不可用,您可以为该文件指定一个后备位置?

This first answer may not work in all browsers.第一个答案可能不适用于所有浏览器。 You could just have some/remote/script.js set some variable "loaded=true" and then check it in the next script block.您可以让 some/remote/script.js 设置一些变量“loaded=true”,然后在下一个脚本块中检查它。

<script>
loaded=false
</script>
<script src="some/remote/script.js"></script>
<script>
if(loaded==false){
  //do what you want here if it didn't load
}
</script>

There's a good article on this here: http://happyworm.com/blog/2010/01/28/a-simple-and-robust-cdn-failover-for-jquery-14-in-one-line/这里有一篇很好的文章: http://happyworm.com/blog/2010/01/28/a-simple-and-robust-cdn-failover-for-jquery-14-in-one-line/

This came in handy for me on a site using the Microsoft Ajax CDN to get jquery.在使用 Microsoft Ajax CDN 获取 jquery 的站点上,这对我来说非常方便。 We had a few customers whose machines did not trust the SSL certificate from the CDN when we used jquery on HTTPS pages.当我们在 HTTPS 页面上使用 jquery 时,我们有一些客户的机器不信任来自 CDN 的 SSL 证书。 A local fallback is a good way to fix that problem.本地回退是解决该问题的好方法。

We determined whether or not to inject the fallback by checking a variable the the script would have otherwise added to the global namespace.我们通过检查脚本将添加到全局命名空间中的变量来确定是否注入回退。 eg例如

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">    </script>
<script type="text/javascript">
//<![CDATA[
if (typeof jQuery == 'undefined') {document.write(unescape("%3Cscript src='/Scripts/jquery.min.js' type='text/javascript' %3E%3C/script%3E"));}
//]]>
</script>

( Edited: First attempt was wrong ) 编辑:第一次尝试是错误的

<script src="some/remote/script.js">
    // Set a flag in the above script
</script>
<script>
    if ( ! flag ) {
        // This code runs if script.js fails to load for some reason
    }
</script>

<object data="http://cdn/file.png" type="image/png">
    <!-- You can nest objects in here too -->
    <img src="http://local/file.png" alt="Fallback Image"/>
</object>

So I suppose you could use the script method for everything;所以我想你可以对所有事情都使用脚本方法; in the event the remote files fail to load, use the fallback code to change all paths to point to your backup server.如果远程文件无法加载,请使用回退代码更改所有路径以指向您的备份服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM