使用 Google 托管的 jQuery 的最佳方法,但退回到我在 Google 上的托管库失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1014203/
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-08-26 10:24:43  来源:igfitidea点击:

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

jquerycdngoogle-ajax-libraries

提问by Nosredna

What would be a good way to attempt to load the hosted jQuery at Google(or other Google hosted libs), but load my copy of jQuery if the Google attempt fails?

尝试在 Google(或其他 Google 托管库)上加载托管的 jQuery,但如果 Google 尝试失败,则加载我的 jQuery 副本的好方法是什么?

I'm not saying Google is flaky. There are cases where the Google copy is blocked (apparently in Iran, for instance).

我并不是说谷歌是脆弱的。在某些情况下,Google 副本被阻止(例如,显然在伊朗)。

Would I set up a timer and check for the jQuery object?

我会设置一个计时器并检查 jQuery 对象吗?

What would be the danger of both copies coming through?

两个副本都通过会有什么危险?

Not really looking for answers like "just use the Google one" or "just use your own." I understand those arguments. I also understand that the user is likely to have the Google version cached. I'm thinking about fallbacks for the cloud in general.

并不是真的在寻找“只使用谷歌的”或“只使用你自己的”之类的答案。我理解这些论点。我也了解用户可能会缓存 Google 版本。我正在考虑一般云的回退。



Edit: This part added...

编辑:这部分添加了...

Since Google suggests using google.load to load the ajax libraries, and it performs a callback when done, I'm wondering if that's the key to serializing this problem.

由于 Google 建议使用 google.load 加载 ajax 库,并且在完成后执行回调,我想知道这是否是序列化此问题的关键。

I know it sounds a bit crazy. I'm just trying to figure out if it can be done in a reliable way or not.

我知道这听起来有点疯狂。我只是想弄清楚它是否可以以可靠的方式完成。



Update: jQuery now hosted on Microsoft's CDN.

更新:jQuery 现在托管在 Microsoft 的 CDN 上。

http://www.asp.net/ajax/cdn/

http://www.asp.net/ajax/cdn/

采纳答案by Rony

You can achieve it like this:

你可以这样实现:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

<script>
       window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>

This should be in your page's <head>and any jQuery ready event handlers should be in the <body>to avoid errors (although it's not fool-proof!).

这应该在您的页面中,<head>并且任何 jQuery 就绪事件处理程序都应该在 中<body>以避免错误(尽管它不是万无一失的!)。

One more reason to notuse Google-hosted jQueryis that in some countries, Google's domain name is banned.

使用 Google 托管的jQuery 的另一个原因是,在某些国家/地区,Google 的域名是被禁止的。

回答by BenjaminRH

The easiest and cleanest way to do this by far:

迄今为止最简单、最干净的方法:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="path/to/your/jquery"><\/script>')</script>

回答by artlung

This seems to work for me:

这似乎对我有用:

<html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// has the google object loaded?
if (window.google && window.google.load) {
    google.load("jquery", "1.3.2");
} else {
    document.write('<script type="text/javascript" src="http://joecrawford.com/jquery-1.3.2.min.js"><\/script>');
}
window.onload = function() {
    $('#test').css({'border':'2px solid #f00'});
};
</script>
</head>
<body>
    <p id="test">hello jQuery</p>
</body>
</html>

The way it works is to use the googleobject that calling http://www.google.com/jsapiloads onto the windowobject. If that object is not present, we are assuming that access to Google is failing. If that is the case, we load a local copy using document.write. (I'm using my own server in this case, please use your own for testing this).

它的工作方式是使用google调用http://www.google.com/jsapi加载到window对象上的对象。如果该对象不存在,我们假设对 Google 的访问失败。如果是这种情况,我们将使用document.write. (在这种情况下,我使用的是我自己的服务器,请使用您自己的服务器进行测试)。

I also test for the presence of window.google.load- I could also do a typeofcheck to see that things are objects or functions as appropriate. But I think this does the trick.

我还测试是否存在window.google.load- 我还可以进行typeof检查以查看事物是否为对象或函数。但我认为这可以解决问题。

Here's just the loading logic, since code highlighting seems to fail since I posted the whole HTML page I was testing:

这只是加载逻辑,因为自从我发布了我正在测试的整个 HTML 页面后,代码突出显示似乎失败了:

if (window.google && window.google.load) {
    google.load("jquery", "1.3.2");
} else {
    document.write('<script type="text/javascript" src="http://joecrawford.com/jquery-1.3.2.min.js"><\/script>');
}

Though I must say, I'm not sure that if this is a concern for your site visitors you should be fiddling with the Google AJAX Libraries APIat all.

虽然我必须说,我不确定如果这是您的网站访问者所关心的问题,您是否应该摆弄Google AJAX 库 API

Fun fact: I tried initially to use a try..catch block for this in various versions but could not find a combination that was as clean as this. I'd be interested to see other implementations of this idea, purely as an exercise.

有趣的事实我最初尝试在各种版本中为此使用 try..catch 块,但找不到像这样干净的组合。我很想看看这个想法的其他实现,纯粹是作为一个练习。

回答by Emanuel Kluge

If you have modernizr.js embedded on your site, you can use the built-in yepnope.js to load your scripts asynchronously - among others jQuery (with fallback).

如果您的站点中嵌入了 Modernizr.js,则可以使用内置的 yepnope.js 异步加载脚本 - 其中包括 jQuery(带有回退)。

Modernizr.load([{
    load : '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'
},{
    test : window.jQuery,
    nope : 'path/to/local/jquery-1.7.2.min.js',
    both : ['myscript.js', 'another-script.js'],
    complete : function () {
        MyApp.init();
    }
}]);

This loads jQuery from the Google-cdn. Afterwards it's checked, if jQuery was loaded successfully. If not ("nope"), the local version is loaded. Also your personal scripts are loaded - the "both" indicates, that the load-process is iniated independently from the result of the test.

这将从 Google-cdn 加载 jQuery。然后检查jQuery是否加载成功。如果不是(“nope”),则加载本地版本。还加载了您的个人脚本 - “两者”表示加载过程是独立于测试结果启动的。

When all load-processes are complete, a function is executed, in the case 'MyApp.init'.

当所有加载过程完成时,将执行一个函数,在“MyApp.init”的情况下。

I personally prefer this way of asynchronous script loading. And as I rely on the feature-tests provided by modernizr when building a site, I have it embedded on the site anyway. So there's actually no overhead.

我个人更喜欢这种异步脚本加载方式。由于我在构建站点时依赖于 Modernizr 提供的功能测试,因此无论如何我都将其嵌入到站点中。所以实际上没有开销。

回答by Acorn

There are some great solutions here, but I'll like to take it one step further regarding the local file.

这里有一些很好的解决方案,但我想在本地文件方面更进一步。

In a scenario when Google does fail, it should load a local source but maybe a physical file on the server isn't necessarily the best option. I bring this up because I'm currently implementing the same solution, only I want to fall back to a local file that gets generated by a data source.

在 Google 确实失败的情况下,它应该加载本地源,但服务器上的物理文件不一定是最佳选择。我提出这个问题是因为我目前正在实施相同的解决方案,只是我想回退到由数据源生成的本地文件。

My reasons for this is that I want to have some piece of mind when it comes to keeping track of what I load from Google vs. what I have on the local server. If I want to change versions, I'll want to keep my local copy synced with what I'm trying to load from Google. In an environment where there are many developers, I think the best approach would be to automate this process so that all one would have to do is change a version number in a configuration file.

我这样做的原因是,当涉及到跟踪我从 Google 加载的内容与我在本地服务器上加载的内容时,我想有所保留。如果我想更改版本,我会希望我的本地副本与我尝试从 Google 加载的内容保持同步。在一个有很多开发人员的环境中,我认为最好的方法是自动化这个过程,这样所有人只需更改配置文件中的版本号。

Here's my proposed solution that should work in theory:

这是我提出的理论上应该可行的解决方案:

  • In an application configuration file, I'll store 3 things: absolute URL for the library, the URL for the JavaScript API, and the version number
  • Write a class which gets the file contents of the library itself (gets the URL from app config), stores it in my datasource with the name and version number
  • Write a handler which pulls my local file out of the db and caches the file until the version number changes.
  • If it does change (in my app config), my class will pull the file contents based on the version number, save it as a new record in my datasource, then the handler will kick in and serve up the new version.
  • 在应用程序配置文件中,我将存储 3 项内容:库的绝对 URL、JavaScript API 的 URL 和版本号
  • 编写一个类来获取库本身的文件内容(从应用程序配置中获取 URL),将其与名称和版本号一起存储在我的数据源中
  • 编写一个处理程序,将我的本地文件从数据库中拉出并缓存文件,直到版本号更改。
  • 如果它确实发生了变化(在我的应用程序配置中),我的类将根据版本号提取文件内容,将其保存为我的数据源中的新记录,然后处理程序将启动并提供新版本。

In theory, if my code is written properly, all I would need to do is change the version number in my app config then viola! You have a fallback solution which is automated, and you don't have to maintain physical files on your server.

理论上,如果我的代码编写正确,我需要做的就是更改我的应用程序配置中的版本号,然后 viola!您有一个自动化的后备解决方案,并且您不必在服务器上维护物理文件。

What does everyone think? Maybe this is overkill, but it could be an elegant method of maintaining your AJAX libraries.

大家觉得呢?也许这有点矫枉过正,但它可能是维护 AJAX 库的一种优雅方法。

Acorn

橡子

回答by alex

if (typeof jQuery == 'undefined') {
// or if ( ! window.jQuery)
// or if ( ! 'jQuery' in window)
// or if ( ! window.hasOwnProperty('jQuery'))    

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '/libs/jquery.js';

  var scriptHook = document.getElementsByTagName('script')[0];
  scriptHook.parentNode.insertBefore(script, scriptHook);

}

After you attempt to include Google's copy from the CDN.

在您尝试从 CDN 中包含 Google 的副本之后。

In HTML5, you don't need to set the typeattribute.

在 HTML5 中,您不需要设置该type属性。

You can also use...

您还可以使用...

window.jQuery || document.write('<script src="/libs/jquery.js"><\/script>');

回答by Edward Olamisan

You might want to use your local file as a last resort.

您可能希望使用本地文件作为最后的手段。

Seems as of now jQuery's own CDN does not support https. If it did you then might want to load from there first.

目前看来 jQuery 自己的 CDN 不支持 https。如果是这样,那么您可能想先从那里加载。

So here's the sequence: Google CDN => Microsoft CDN => Your local copy.

所以这里的顺序是:Google CDN => Microsoft CDN => 您的本地副本。

<!-- load jQuery from Google's CDN -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<!-- fallback to Microsoft's Ajax CDN -->
<script> window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js">\x3C/script>')</script> 
<!-- fallback to local file -->
<script> window.jQuery || document.write('<script src="Assets/jquery-1.8.3.min.js">\x3C/script>')</script> 

回答by neiker

Conditionally load latest/legacy jQuery version and fallback:

有条件地加载最新/旧版 jQuery 版本并回退:

<!--[if lt IE 9]>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/public/vendor/jquery-legacy/dist/jquery.min.js">\x3C/script>')</script>
<![endif]-->
<!--[if gte IE 9]><!-->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="/public/vendor/jquery/dist/jquery.min.js">\x3C/script>')</script>
<!--<![endif]-->

回答by Serdar

Because of the Google's banning problem I prefer to use Microsoft's cdn http://www.asp.net/ajaxlibrary/cdn.ashx

由于谷歌的禁止问题,我更喜欢使用微软的 cdn http://www.asp.net/ajaxlibrary/cdn.ashx

回答by ninjagecko

  • Step 1: Did jQuery fail to load? (check jQueryvariable)
  • 第 1 步:jQuery 加载失败了吗?(检查jQuery变量)

How to check a not-defined variable in JavaScript

如何在 JavaScript 中检查未定义的变量

  • Step 2: Dynamically import (the backup) javascript file
  • 第 2 步:动态导入(备份)javascript 文件

How do I include a JavaScript file in another JavaScript file?

如何在另一个 JavaScript 文件中包含一个 JavaScript 文件?