4

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
})(); 
tsds
  • 8,700
  • 12
  • 62
  • 83

4 Answers4

6

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);
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 1
    But what if where is already 3-rd party jQuery in the global namespace – tsds Oct 29 '11 at 07:21
  • Will jQuery remove 3rd party global jQuery instance? – tsds Oct 29 '11 at 07:22
  • @tsds, well, I don't know what you mean by `3rd party jQuery`, but the `noconflict()` method will be called on that object, so it should unregister itself from the global namespace. – Frédéric Hamidi Oct 29 '11 at 07:23
2
var jQuery, $;
jQuery = $ = window.jQuery;
delete window.jQuery;
delete window.$;
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
2

You can remove it with .noConflict:

var localjQuery = jQuery.noConflict(true);

But it will have been in global scope before that call...

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

Found this post while trying to figure out how to inject a completely independent jQuery instance with custom extension methods onto a webpage through GreaseMonkey/Tampermonkey, and get around the Chrome sandbox. Needless to say I needed a little more than provided, below is what I ended up with.

Below is the injected code body and some other methods I'm sure would help others get started. I inject this onto every web page so that I can access this instance through the dev console or through other tampermonkey scripts. I gave it the alias "z". It lazily loads so that it doesn't slow down pages that aren't using it.

To load, a call needs to be made to z(), z.ProcessWaitList(), or by adding functions to ZWaitList before the z script has been loaded.

Note the //BEGIN_INJECTION// and //END_INJECTION// tags as well as the conditional include tags /... and .../. The code inside the conditional include tags will only be included in the actual code that is injected onto the page. This prevents duplicate automatic executions where the script runs once in GreaseMonkey then again once injected.

(function ZInjectionContainer() {
    if(!document.querySelector('script[id="ZInjectionContainer"]')){
        //BEGIN_INJECTION//
        /*... z = (function (_jQuery, _$) { ...*/    

        function SubstrBetween(s, start,end){ return s.substring(s.indexOf(start) + start.length, s.lastIndexOf(end));}

        function AppendScript(id, src, callback){
            var js = document.querySelector('script[id="'+ id +'"]');
            if(!js){ 
                js = document.createElement('script'); js.id = id; js.type = 'text/javascript';
                document.getElementsByTagName('body')[0].appendChild(js); 
            } 
            if(callback)  js.onload = callback;     
            if(src && String(src).endsWith('.js')) js.src = src; 
            else if(src)js.text += "\n" + String(src); 
            return js;
        }  

        function ProcessWaitList(){
            function process(){ console.log('  Processing WaitList.');  while(ZWaitList.length > 0){   ZWaitList.shift().call(); } }
            if(typeof ZWaitList == 'undefined') ZWaitList = [];            
            if(Array.isArray(ZWaitList) && ZWaitList.length > 0){      
                if(!IsInitialized()) {
                    console.log('ZWaitList sizeof ' + ZWaitList.length + ' detected.  Auto Initializing');  
                    ZInitialize(process);                        
                }
                else{ process(); } 
            }      
        }

        function ZInitialize(callback) {  
            var _version = 'jquery-2.2.0.min';
            AppendScript(_version, 'https://code.jquery.com/'+ _version +'.js',function(){
                z = jQuery.noConflict(true);  
                jQuery = _jQuery; $ = _$;  
                z.extend(createLocalInstance());               
                console.log(' Loaded jQuery-' + z().jquery + ' as z. Page Version is jQuery-' + (_jQuery ? _jQuery().jquery : 'undefined'));                                                         
                z(document).ready(function(){ 
                    console.log('    document loaded'); 
                    if(callback) z(callback); 
                    if(callback != ProcessWaitList){ ProcessWaitList();}
                });
            });                 
        }; 

        function IsInitialized(){
            return (typeof z !== 'undefined' && typeof z=== 'function' && !String(z).startsWith(ZInitialize.toString()));
        }

        function createLocalInstance(){
            var local = ZInitialize;
            local.IsInitialized = IsInitialized;
            local.SubstrBetween = SubstrBetween;
            local.AppendScript = AppendScript;
            local.ProcessWaitList = ProcessWaitList;
            return local;
        }

    /*... 
        if(typeof z == 'undefined')  {z = createLocalInstance();}  
        else if (typeof z !== 'function' || !String(z).startsWith(ZInitialize.toString())) {
            console.log('Error.  z is already defined as: '  + z +'\n Overwriting anyway');
            z = createLocalInstance();
        }

        ProcessWaitList();
        return z;   
    })(typeof jQuery !== 'undefined' ?  jQuery : null, typeof $ !== 'undefined' ?  $ : null); 
     ...*/  
    //END_INJECTION//   

        var inject = SubstrBetween(ZInjectionContainer.toString(),"//BEGIN_INJECTION//", "/"+"/END_INJECTION//");
        inject = inject.split('/*...').join('').split('...*/').join('');
        AppendScript("ZInjectionContainer", inject);
    }
})();   

Other scripts that use the functionality call it like this:

function RemoveStupidStuff(){    
    //Example code
    z('td.logo1').parents('table').remove();
    z('#bodyarea').prev().remove();
    z('#bodyarea').css('padding','0')
    z('#bodyarea #mcol').prev().remove();
}

function FixIndexPage(){
     //Example code - Remove show image on hover and instead just make it the thumbnail
    console.log('making the index page less crappy');
    z('#bodyarea #mcol table[width="75%"] tr td table.lista').attr('id','thegoods').css('width','100%');;
    z('#thegoods tr:not(:first-child)').addClass('listing');

    var listings = z('.listing')
    for(var i=0; i < listings.length; i++){       
        var row = listings[i];
        var thumb = z(row.children[0]).find('a')[0];
        var hoverimg = z(row.children[1]).find('a')[0];
        var link = z.SubstrBetween(hoverimg.onmouseover.toString(), "<img src=", " width=");
        thumb.href = hoverimg.href;               
        z(thumb).find('img').attr('src', link).attr('width','350px'); 
    }    
}

var operations = [RemoveStupidStuff];
if(location.search.indexOf('page=index')>=0){
    operations.push(FixIndexPage);
}

console.log('pushin site fixes to waitlist');
if(typeof ZWaitList === 'undefined') 
    ZWaitList = operations;
else {
    ZWaitList = ZWaitList.concat(operations);
    z.ProcessWaitList();
}

Here is what the Chrome Dev Console will output using the above code. Notice it's running in different VM's and everything.

VM300:59 pushin site fixes to waitlist
VM298:24 ZWaitList sizeof 2 detected.  Auto Initializing
VM298:35  Loaded jQuery-2.2.0 as z. Page Version is jQuery-1.6.4
VM298:37     document loaded
VM298:20   Processing WaitList.
VM300:30 making the index page less crappy
VM298:20   Processing WaitList.
Derek Ziemba
  • 2,467
  • 22
  • 22