如果未加载,则从外部源加载 jQuery

发布于 2024-10-09 04:04:42 字数 262 浏览 3 评论 0原文

从源加载 jQuery

我喜欢做的是删除本地 jquery.js 并拥有 它托管在其他地方。但如果谷歌宕机了怎么办?所以 让我们编写一个使用其他源的后备代码,如果 jQuery “仍然”未加载...

我做了这个测试用例,但它似乎不起作用,也许 有人可以帮助我:

http://jsfiddle.net/RBz4n

load jQuery from source

What I like to do is to drop my local jquery.js and have
it hosted somewhere else. But what if Google is down? So
let's code a fallback that uses another source if jQuery
is "still" not loaded...

I made this test case but it does not seem to work, maybe
someone can help me out:

http://jsfiddle.net/RBz4n

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

遮了一弯 2024-10-16 04:04:42

这工作得相当好(来自 HTML5 Boilerplate):

<!-- Grab Google CDN's jQuery. fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>

This works fairly well (from HTML5 Boilerplate):

<!-- Grab Google CDN's jQuery. fall back to local if necessary -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>
锦爱 2024-10-16 04:04:42

这是一个纯 JavaScript 解决方案,首先检测 jQuery 是否可用。如果没有,它会尝试 CDN 版本。如果该版本不可用,它将尝试本地版本。处理 404 错误。我在一个不知道该网站是否包含 jQuery 的解决方案中使用它。

<script>
if (typeof jQuery === "undefined") {
  loadjQuery("//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js", verifyJQueryCdnLoaded);
} else 
  main();

function verifyJQueryCdnLoaded() {
  if (typeof jQuery === "undefined")
    loadjQuery("script/jquery-1.6.1.js", main);
  else
    main();
}

function loadjQuery(url, callback) {
  var script_tag = document.createElement('script');
  script_tag.setAttribute("src", url)
  script_tag.onload = callback; // Run callback once jQuery has loaded
  script_tag.onreadystatechange = function () { // Same thing but for IE
    if (this.readyState == 'complete' || this.readyState == 'loaded') callback();
  }
  script_tag.onerror = function() {
    loadjQuery("script/jquery-1.6.1.js", main);
  }
  document.getElementsByTagName("head")[0].appendChild(script_tag);
}

function main() {
  if (typeof jQuery === "undefined")
    alert("jQuery not loaded.");

  $(document).ready(function () {
    // Rest of your code here...
  });

}

</script>

Here is a pure javascript solution that starts out by detecting if jQuery is available. If not, it tries the CDN version. If that's not available, it tries the local version. Handles 404 errors. I use this in a solution that doesn't know whether the website has included jQuery.

<script>
if (typeof jQuery === "undefined") {
  loadjQuery("//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js", verifyJQueryCdnLoaded);
} else 
  main();

function verifyJQueryCdnLoaded() {
  if (typeof jQuery === "undefined")
    loadjQuery("script/jquery-1.6.1.js", main);
  else
    main();
}

function loadjQuery(url, callback) {
  var script_tag = document.createElement('script');
  script_tag.setAttribute("src", url)
  script_tag.onload = callback; // Run callback once jQuery has loaded
  script_tag.onreadystatechange = function () { // Same thing but for IE
    if (this.readyState == 'complete' || this.readyState == 'loaded') callback();
  }
  script_tag.onerror = function() {
    loadjQuery("script/jquery-1.6.1.js", main);
  }
  document.getElementsByTagName("head")[0].appendChild(script_tag);
}

function main() {
  if (typeof jQuery === "undefined")
    alert("jQuery not loaded.");

  $(document).ready(function () {
    // Rest of your code here...
  });

}

</script>
╰◇生如夏花灿烂 2024-10-16 04:04:42

您的脚本的问题在于您没有等待脚本加载然后测试 jQuery 是否已加载。使用类似这样的东西:

function loadScript(src, callback) {
    var head=document.getElementsByTagName('head')[0];
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.onreadystatechange = function () {
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
            callback();
        }
    }
    script.onload = callback;
    script.src = src;
    head.appendChild(script);
}

function isjQueryLoaded() {
    return (typeof jQuery !== 'undefined');
}

function tryLoadChain() {
    var chain = arguments;
    if (!isjQueryLoaded()) {
        if (chain.length) {
            loadScript(
                chain[0],
                function() {
                    tryLoadChain.apply(this, Array.prototype.slice.call(chain, 1));
                }
            );
        } else {
            alert('not loaded!');
        }
    } else {
        alert('loaded!');
    }
}

tryLoadChain(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',
    'http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js',
    'mine.js');

The problem with your script is that you're not waiting for the script to load before testing whether jQuery has been loaded. Use something like this instead:

function loadScript(src, callback) {
    var head=document.getElementsByTagName('head')[0];
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.onreadystatechange = function () {
        if (this.readyState == 'complete' || this.readyState == 'loaded') {
            callback();
        }
    }
    script.onload = callback;
    script.src = src;
    head.appendChild(script);
}

function isjQueryLoaded() {
    return (typeof jQuery !== 'undefined');
}

function tryLoadChain() {
    var chain = arguments;
    if (!isjQueryLoaded()) {
        if (chain.length) {
            loadScript(
                chain[0],
                function() {
                    tryLoadChain.apply(this, Array.prototype.slice.call(chain, 1));
                }
            );
        } else {
            alert('not loaded!');
        }
    } else {
        alert('loaded!');
    }
}

tryLoadChain(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',
    'http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js',
    'mine.js');
永言不败 2024-10-16 04:04:42

问题

如果您使用 Firebug 并查看 jQuery 的加载位置,您可以看到 Google 已成功加载它。为什么它似乎不起作用?因为请求是异步的,并且当您的脚本同步运行时,它会在加载第一个脚本之前执行所有步骤。

所以:

  1. jQuery 不存在。
  2. 添加 SCRIPT 元素以从 Google 加载(浏览器发送请求并继续执行脚本)
  3. jQuery 不存在 添加另一个源
  4. ...

等等。

解决

方案 您应该做的是附加到您的 onLoad 事件脚本加载元素并在加载后检查 jQuery。

与向互联网上的某个服务器发送请求并获取结果进行处理相比,脚本的执行速度快如闪电。

附加说明

正如我所读到的,您在使用此技术检测 404 时会遇到问题。建议的方法是使用 Ajax (XHR),然后附加脚本元素并向其中添加收到的内容。对于所有浏览器来说,这将是最可靠的方法。

The problem

If you use Firebug and see where jQuery gets loaded you can see taht Google successfully loaded it. Why it doesn't seem to work? Because requests are asynchronous and while your script runs synchronously it executes all steps before the first script gets loaded.

So:

  1. jQuery not present.
  2. Add SCRIPT element to load from Google (browser sends a request and continues execution of the script)
  3. jQuery not present add another source
  4. ...

etc etc.

Solution

What you should do is attach to onLoad event of your script loading elements and check for jQuery after they've loaded.

Script executes lightning fast compared to sending a request out to some server on the internet and getting results back for processing.

Additional notes

As I've read you're going to have problems detecting 404s using this technique. Suggested way would be to use Ajax (XHR) and then attach script element and add received content to it. This would be the most reliable way of doing it for all browsers.

遮了一弯 2024-10-16 04:04:42

罗杰的回答很荒谬。在这里,使用它,它的两行。

<script>window.jQuery || document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"><\/script>')</script> 
<script>window.jQuery || document.write('<script src="Content/Scripts/jquery-1.9.1.min.js"><\/script>')</script>

Roger's answer is rediculous. Here, use this instead, its 2 lines.

<script>window.jQuery || document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"><\/script>')</script> 
<script>window.jQuery || document.write('<script src="Content/Scripts/jquery-1.9.1.min.js"><\/script>')</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文