decoupling jquery, sizzle?

无人久伴 提交于 2019-12-02 22:32:24
Nick Craver

There's no need for Sizzle to be included in the jQuery build. It can be removed...the jQuery code all references Sizzle., you can just grab/compile jQuery yourself (including Sizzle beforehand) and have it exposed to any other library (not actually including it in the compiled version, just as an extern to the closure compiler).


Here's the option to leave it embedded, but expose Sizzle for outside use:

If you know jQuery will be used (dependency), just add this after jQuery:

​window.Sizzle = jQuery.find;

This will re-expose Sizzle as a property you can use.


Here's the manual version to remove Sizzle from being embedded:

In jQuery (version 1.4.3 link) you'll see this :

/*!
 * Sizzle CSS Selector Engine - v1.0
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){
//...
//lots of code!
//...

// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;

})();

Replace that section with only:

(function(){    
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;    
})();

Then all you need to do in include Sizzle before jQuery and it'll work fine.

Here's a fiddle showing it working, including Sizzle directly from github, not embedded in jQuery.

If you want to use the eCSStender CSS3 Selectors Module with the Sizzle bundled in jQuery, you can do that:

eCSStender.addMethod('findBySelector',function(selector){
  var els = [];
  jQuery(selector).each(function(){
    els.push(this);
  });
  return els;
});

There may be an easier way to directly get an actual element collection (rather than a fake one using an array), but it's early yet and my brain isn't working quite yet.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!