Why does the global jQuery object get overwritten after the page loads?
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="te开发者_StackOverflow社区xt/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.
Something is wrong because I get the correct output.
Wow, I feel stupid.
My test code (the part that I hadn't posted in the question) was intentionally calling jQuery.ajax()
on jquery-1.5.2.js
(since this is a reasonably big file for testing progress events). However, I had forgotten that unless one manually sets the dataType
option to something other than script
, jQuery will evaluate any JavaScript that's retrieved by jQuery.ajax()
.
So jQuery was evaluating a new copy of its own source code, and window.jQuery
was therefore getting overwritten.
精彩评论