如何在CDN被阻止/不可用的情况下加载本地脚本文件作为后备? [英] How to load local script files as fallback in cases where CDN are blocked/unavailable?

查看:128
本文介绍了如何在CDN被阻止/不可用的情况下加载本地脚本文件作为后备?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下javascript的CDN:

I’m using a CDN for the following javascript:

  • https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
  • https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js
  • http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js
  • http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js

对于每一个,我怎样才能恢复使用在可能被阻止/不可用的实例中的本地副本?

For each one, how can I revert to using local copy in the instance where it may be blocked/unavailable?

推荐答案

要确认加载了cdn脚本,您可以检查是否存在v ariable / function这个脚本定义,如果它是未定义的 - 然后cdn失败,你需要加载本地脚本副本。

To confirm that cdn script loaded you can check for existence any variable/function this script defines, if it is undefined - then cdn failed and you need to load local script copy.

这个原则基于这样的解决方案:

On this principle are based solutions like that:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.5.1.min.js">\x3C/script>')</script>

(如果没有window.jQuery属性定义的cdn脚本没有加载)。

(if there is no window.jQuery property defined cdn script didn't loaded).

您可以使用此方法构建自己的解决方案。例如,jquery工具提示插件创建 $。tooltip()函数,因此我们可以使用以下代码进行检查:

You may build your own solutions using this method. For instance, jquery tooltip plugin creates $.tooltip() function so we can check it with code like this:

<script>
    if (typeof $.tooltip === 'undefined') {
        document.write('<script src="js/libs/jquery.tooltip.min.js">\x3C/script>');
    }
</script>

这篇关于如何在CDN被阻止/不可用的情况下加载本地脚本文件作为后备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆