【问题标题】:Why does this reach main() yet jQuery is still undefined?为什么这会到达 main() 但 jQuery 仍然未定义?
【发布时间】:2012-01-20 17:08:17
【问题描述】:

我正在尝试修改各种加载器,以便在调用主函数之前可以处理多个脚本。这应该加载 jQuery,然后是 jQueryUI,然后调用 main() 来实际启动用户脚本。但是,它确实会循环,但是当它到达 main() 时,我从 Chrome 中收到一个关于 jQuery 未定义的控制台错误。

!function loader (i) {
        var requires = [ 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'
                       , 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js'
                       ];
        var loadScript = function (i) {
                    var script    = document.createElement('script');
                    script.type   = 'text/javascript';
                    script.src    = requires[i];
                    script.onload = (++i === requires.length) ? function () { loader(i); }
                                                              : function () { main(); }
                    document.head.appendChild(script);
            };

        loadScript(i || 0);
}();

function main () {
    console.log(jQuery.version);
    console.log(jQuery.ui.version);
}

【问题讨论】:

  • !function 是怎么回事?
  • 同(函数{})();
  • 为什么忽略了document.appendChild(script);不是有效操作的错误?
  • 对不起 - 看起来它以某种方式被丢弃在我的复制/粘贴中。 /我编辑:P
  • ianbarker:在用户脚本上下文中,并且使用依赖于 jQuery 的 jQueryUI(以及您可能想要的任何 jQuery 插件),您别无选择。

标签: jquery google-chrome greasemonkey preloader userscripts


【解决方案1】:

这是我想出的最终脚本,如果有人在寻找这种类型的东西。 http://userscripts.org/scripts/review/123588

彼拉多用三元组抓住了其中的一部分。 Nate B 也有一部分,jQuery 使用 jQuery.fn.jquery(但 UI 不一致并使用 jQuery.ui.version)。

对于第 3 方来说,弄清楚如何跳过中间的包装位会很好,但这很有效。 :)

【讨论】:

    【解决方案2】:

    我不认为jQuery.version 是一个有效的属性,它返回undefined。试试$.fn.jquery,看看会发生什么。

    【讨论】:

    • 是的,但这不会导致ReferenceError
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多