【问题标题】:How to encapsulate jQuery?如何封装jQuery?
【发布时间】:2011-10-29 07:11:47
【问题描述】:

我特别想定义本地 jQuery (var jQuery) where
应该存储 jQuery(以及本地 $)。

问题是jQuery直接用window对象操作:

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

这是来自 jQuery 1.6.4 的引用
我该如何解决这个问题?

P.S.:我的特殊问题是为 3-rd 方网站使用编写一些 sn-p
如果我包含 jQuery,可能会出现一些不兼容的问题 那个 3-rd 方 js 代码。目前我正在做以下事情:

// here some license notes about jQuery included
(function() {
    if (typeof jQuery === "undefined") {
        // jQuery code as it is goes here
    }
    // my code
})(); 

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您可以将true 传递给$.noconflict() 以让jQuery 从全局范围中删除其所有变量:

    (function($) {
        var jQuery = $.noconflict(true);
        // From there on, window.jQuery and window.$ are undefined.
        var $ = jQuery;
        // Do something with the local jQuery and $...
    })(jQuery);
    

    【讨论】:

    • 但是如果全局命名空间中已经有 3-rd 方 jQuery 怎么办
    • jQuery 会删除第三方全局 jQuery 实例吗?
    • @tsds,好吧,我不知道你所说的3rd party jQuery 是什么意思,但是noconflict() 方法会在那个对象上被调用,所以它应该从全局命名空间中注销自己。
    【解决方案2】:
    var jQuery, $;
    jQuery = $ = window.jQuery;
    delete window.jQuery;
    delete window.$;
    

    【讨论】:

    • 我不能只删除全局 jQuery,我已经更新了我的问题,请看一下
    【解决方案3】:

    你可以用.noConflict删除它:

    var localjQuery = jQuery.noConflict(true);
    

    但在调用之前它已经在全局范围内......

    【讨论】:

      【解决方案4】:

      在试图弄清楚如何通过 GreaseMonkey/Tampermonkey 将具有自定义扩展方法的完全独立的 jQuery 实例注入到网页上时发现这篇文章,并绕过 Chrome 沙箱。不用说我需要的比提供的多一点,下面是我最终得到的。

      下面是注入的代码体和其他一些我相信会帮助其他人入门的方法。我将它注入到每个网页中,以便我可以通过开发控制台或其他 Tampermonkey 脚本访问此实例。我给它起了别名“z”。它延迟加载,因此它不会减慢不使用它的页面。

      要加载,需要调用 z()、z.ProcessWaitList(),或者在加载 z 脚本之前向 ZWaitList 添加函数。

      注意 //BEGIN_INJECTION// 和 //END_INJECTION// 标签以及条件包含标签 /... 和 .../。条件包含标记内的代码只会包含在注入页面的实际代码中。这可以防止重复的自动执行,其中脚本在 GreaseMonkey 中运行一次,然后再次注入。

      (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);
          }
      })();   
      

      其他使用该功能的脚本这样称呼它:

      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();
      }
      

      这是 Chrome 开发控制台使用上述代码输出的内容。请注意,它在不同的虚拟机和所有东西中运行。

      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.
      

      【讨论】:

        猜你喜欢
        • 2011-02-14
        • 1970-01-01
        • 2012-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多