为什么到达 main() 而 jQuery 仍然未定义?
我正在尝试修改各种加载器,以便在调用主函数之前可以处理多个脚本。这应该加载 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);
}
I'm trying to modify the various loaders out there so multiple scripts can be handled before the main function is called. This should load jQuery, then jQueryUI, and then call main() to actually start the userscript. However, it does loop through, but when it gets to main(), I get a console error from Chrome about jQuery being undefined.
!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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果有人正在寻找此类内容,这是我想出的最终脚本。
http://userscripts.org/scripts/review/123588
彼拉多抓住了其中的一部分,三元。 Nate B 也有一部分,其中 jQuery 使用 jQuery.fn.jquery(但 UI 不一致并使用 jQuery.ui.version)。
对于第 3 方来说,弄清楚如何跳过中间的包装器位本来很好,但这可行。 :)
Here's the final script I came up with, if anyone's looking for this type of thing.
http://userscripts.org/scripts/review/123588
Pilate caught part of it, with the ternary. Nate B also had part of it, with jQuery using jQuery.fn.jquery (but UI being inconsistent and using jQuery.ui.version).
It'd have been nice to figure out how to skip the wrapper bit in the middle, for 3rd party, but this works. :)
我认为
jQuery.version
不是一个有效的属性,它返回undefined
。尝试在那里使用$.fn.jquery
并看看会发生什么。I don't think
jQuery.version
is a valid property, and it returnsundefined
. Try$.fn.jquery
in there instead and see what happens.