[英]Why doesn't jQuery UI see jQuery?
I've built a JavaScript widget that must be embeddable on any third-party site, in any environment. 我已经构建了一个JavaScript小部件,必须可以在任何环境中的任何第三方网站上嵌入。 The widget relies on jQuery and jQuery UI. 该小部件依赖于jQuery和jQuery UI。 I followed the steps in How to embed Javascript widget that depends on jQuery into an unknown environment to add jQuery in a responsible manner -- works great for embedding jQuery. 我按照如何将依赖于jQuery的Javascript小部件嵌入到未知环境中的步骤以负责任的方式添加jQuery - 非常适合嵌入jQuery。 But when I try to add jQuery UI, it fails. 但是当我尝试添加jQuery UI时,它失败了。 Here's the code: 这是代码:
(function(window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js";
script.onload = script.onreadystatechange = function() {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
document.documentElement.childNodes[0].appendChild(script)
}
})(window, document, "1.3.2", function($, jquery_loaded) {
$.getScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js', function(){
console.log('loaded');
});
});
When I run this, I get the 'loaded' mesage, followed by an error saying that "$ is undefined" on line 15 of jquery-ui.js. 当我运行它时,我得到'加载'消息,然后在jquery-ui.js的第15行上出现错误,说“$ is undefined”。 But how can $ be undefined when I'm using $.getScript() to load jQuery UI? 但是当我使用$ .getScript()来加载jQuery UI时,如何才能定义$? And why do I see the message 'loaded' before I get the error? 为什么我在收到错误之前会看到“已加载”消息? According to the jQuery documentation, getScript shouldn't execute the callback until the script has been loaded and executed. 根据jQuery文档,在脚本加载并执行之前,getScript不应该执行回调。
Is there any way I can use this framework to include jQuery UI, or do I need to use a script loader like RequireJS in order to load everything, enforce dependencies, etc.? 有什么方法可以使用这个框架来包含jQuery UI,还是我需要使用像RequireJS这样的脚本加载器来加载所有内容,强制执行依赖项等?
By calling .noConflict(1)
, the same as .noConflict(true)
, you're deleting jQuery, just remove the 1
. 通过调用.noConflict(1)
,与.noConflict(true)
相同,您将删除jQuery,只需删除1
。 The true
argument to .noConflict()
tells jQuery to remove not only $
, but window.jQuery
, which jQuery UI is trying to use afterwards, when it loads. .noConflict()
的true
参数告诉jQuery不仅要删除$
,而且window.jQuery
删除window.jQuery
,jQuery UI在加载后会尝试使用它 。
You can test it here , see there are no errors in the console. 你可以在这里测试一下 ,看看控制台里没有错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.