Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encapsulate jQuery?

Particularly I want to define local jQuery (var jQuery) where
jQuery should be stored (and also local $).

The problem is that jQuery operates directly with window object:

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);

this is a citation from jQuery 1.6.4
How can I workaround this?

P.S.: my particular problem is to write some snippet for 3-rd party website use
and if I include jQuery there may appear some incompatibilities with that 3-rd party js code. Currently I'm doing the following:

// here some license notes about jQuery included
(function() {
    if (typeof jQuery === "undefined") {
        // jQuery code as it is goes here
    }
    // my code
})(); 
like image 570
tsds Avatar asked Dec 22 '22 07:12

tsds


1 Answers

You can pass true to $.noconflict() to have jQuery remove all its variables from the global scope:

(function($) {
    var jQuery = $.noconflict(true);
    // From there on, window.jQuery and window.$ are undefined.
    var $ = jQuery;
    // Do something with the local jQuery and $...
})(jQuery);
like image 143
Frédéric Hamidi Avatar answered Jan 04 '23 16:01

Frédéric Hamidi