在加载DOM后如何运行jQuery的后备副本? [英] How can I run a fallback copy of jQuery after the DOM is loaded?

查看:95
本文介绍了在加载DOM后如何运行jQuery的后备副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是结束正文标记上方的< script> 标记中的第一行代码在我的文档中(它指定在Google的CDN失败的情况下运行本地服务的jQuery副本):

The following are the first lines of code in a <script> tag just above the closing body tag in my document (it specifies that a locally-served copy of jQuery is run in the event that Google's CDN fails):

if(!window.jQuery){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/js/jquery.js';
    var scriptHook = document.getElementsByTagName('script')[0];
    scriptHook.parentNode.insertBefore(script, scriptHook);
}


jQuery(document).ready(function($){
// page behaviors
});

它确实执行成功,因为如果我的电脑没有连接到互联网(这是本地服务的页面),插入了jQuery的本地副本。但是,下面的 document.ready()部分不会执行。我猜这是因为它在jQuery的后备副本生效之前被调用。什么是以某种方式延迟执行的正确做法,以便jQuery的任何副本都能正常工作?

It does execute successfully, in the sense that if my computer is not connected to the Internet (this is a locally-served page), the local copy of jQuery is inserted. However, the document.ready() section below does not execute. I'm guessing this is because it is invoked before the fallback copy of jQuery takes effect. What's the proper practice for somehow "delaying" its execution so that either copy of jQuery will work properly?

推荐答案

你需要成为确保在调用 jQuery 之前,您要附加到dom的脚本已完成加载。您可以使用此处描述的技术执行此操作:

You need to be sure that the script you are appending to the dom has finished loading before calling jQuery. You can do this with the technique described here:

if(!window.jQuery){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '/js/jquery.js';
    script.onreadystatechange= function () {
      if (this.readyState == 'complete') jQueryLoaded();
    }
    script.onload = jQueryLoaded;
    var scriptHook = document.getElementsByTagName('script')[0];
    scriptHook.parentNode.insertBefore(script, scriptHook);
}

function jQueryLoaded() {  };

您还可以将AjQuery内容作为Ajax请求获取,创建一个脚本标记,将其作为正文脚本并附加它。那也行。

You can also fetch the jQuery contents as an Ajax request, create a script tag with those as the body of the script and append it. That would also work.

这篇关于在加载DOM后如何运行jQuery的后备副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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