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.
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 thedataTypeoption 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.jQuerywas therefore getting overwritten.