为什么页面加载后全局 jQuery 对象会被覆盖?
我正在编写一个包含在自执行函数中的 jQuery 扩展:
(function($) {
// global variables for the purposes of this test
__$ = $;
__$support = $.support;
$.support.abc = "123";
// Setup for my extension goes here.
})(jQuery);
在我的测试页面上,我有
<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script type="text/javascript" src="myplugin.js"></script>
<script type="text/javascript">
$(function() {
console.log(__$ === $); // false
console.log(__$support === $.support); // false
console.log($.support.abc); // undefined
});
</script>
为什么会发生这种情况?我没有其他脚本或 jQuery 插件可能会覆盖 jQuery
对象。
我无法找到 jQuery 源代码本身在文档准备好后覆盖 jQuery
对象的代码。有什么想法吗?
如果无法避免这种情况,那么在文档准备好后仍可以访问的 jQuery.support 对象上定义新属性的正确过程是什么?
编辑:我省略了测试代码的关键部分,该部分无意中重新评估了 jQuery 源代码 - 并解释了为什么会出现此问题。请参阅下面我的回答。
I'm writing a jQuery extension contained in a self executing function:
(function($) {
// global variables for the purposes of this test
__$ = $;
__$support = $.support;
$.support.abc = "123";
// Setup for my extension goes here.
})(jQuery);
On my test page, I have
<script type="text/javascript" src="jquery-1.5.2.js"></script>
<script type="text/javascript" src="myplugin.js"></script>
<script type="text/javascript">
$(function() {
console.log(__$ === $); // false
console.log(__$support === $.support); // false
console.log($.support.abc); // undefined
});
</script>
Why does this happen? I have no other scripts or jQuery plugins that might overwrite the jQuery
object.
I haven't been able to find what code in the jQuery source itself overwrites the jQuery
object after the document is ready. Any ideas?
If there's no way to avoid this, what would be the correct procedure for defining new properties on the jQuery.support
object that can still be accessed after the document is ready?
EDIT: I omitted a critical part of my test code that inadvertently reevaluated the jQuery source -- and explains why this issue was happening. See my answer below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出了点问题,因为我得到了正确的输出。
Something is wrong because I get the correct output.
哇,我感觉自己很蠢。
我的测试代码(我没有在问题中发布的部分)有意在
jquery-1.5.2.js
上调用jQuery.ajax()
(因为这是用于测试进度事件的相当大的文件)。但是,我忘记了,除非手动将dataType
选项设置为script
以外的其他内容,否则 jQuery 将评估由jQuery.ajax()< 检索到的任何 JavaScript /代码>。
因此 jQuery 正在评估其自己源代码的新副本,因此
window.jQuery
被覆盖。Wow, I feel stupid.
My test code (the part that I hadn't posted in the question) was intentionally calling
jQuery.ajax()
onjquery-1.5.2.js
(since this is a reasonably big file for testing progress events). However, I had forgotten that unless one manually sets thedataType
option to something other thanscript
, jQuery will evaluate any JavaScript that's retrieved byjQuery.ajax()
.So jQuery was evaluating a new copy of its own source code, and
window.jQuery
was therefore getting overwritten.