javascript 如果不在线,从 Google 或本地加载 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6115132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:31:56  来源:igfitidea点击:

Loading jQuery from Google or locally if not online

javascriptjqueryhtmlcssasp.net-mvc

提问by JudyJ

Right now I have the following links in my code:

现在我的代码中有以下链接:

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>

etc ...

等等 ...

I'd like to make use of the google.com cached copies. I heard google is the best source but please correct me if I am wrong.

我想使用 google.com 缓存的副本。我听说谷歌是最好的来源,但如果我错了,请纠正我。

Anyway is it possible for me to code my application so it uses code from google if available and locally if not. FYI I am using Microsoft MVC3 and the Msoft cloud servers.

无论如何,我是否可以对我的应用程序进行编码,以便它使用来自谷歌的代码(如果可用)和本地代码(如果没有)。仅供参考,我正在使用 Microsoft MVC3 和 Msoft 云服务器。

Thanks

谢谢

回答by isNaN1247

Sure, check out how they do it in HTML5 boilerplate.

当然,看看他们是如何在HTML5 样板文件中做到的。

If you take a look at the bottom of the index.html filewithin the GitHub repo, you'll see the following...

如果您查看GitHub 存储库中index.html 文件底部,您将看到以下内容...

<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/X.X.X/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="local/jquery-X.X.X.min.js">\x3C/script>')</script>

NB: In the code snippet above X.X.Xshould be replaced with the jQuery version number that you're using (e.g. 1.8.2).

注意:在上面的代码片段中,XXX应该替换为您正在使用的 jQuery 版本号(例如1.8.2)。

How does it work?

它是如何工作的?

  1. First, an attempt is made to grab the CDN version (Google's CDN url is used above, but of course you could link to any source you like).
  2. Immediately afterwards, we check for the jQueryglobal object.
  3. If jQuerydoes not exist, the obvious assumption is that we didn't manage to get the code from the CDN, so then we document.writea script tag to get a copy from a local source instead.
  1. 首先,尝试获取 CDN 版本(上面使用了 Google 的 CDN 网址,但当然您可以链接到您喜欢的任何来源)。
  2. 紧接着,我们检查jQuery全局对象。
  3. 如果jQuery不存在,明显的假设是我们没有设法从 CDN 获取代码,因此我们document.write使用脚本标签从本地源获取副本。

回答by jessegavin

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")">\x3C/script>')</script>