Upgrade to Pro — share decks privately, control downloads, hide ads and more …

jQuery Selector 源码剖析

jQuery Selector 源码剖析

分析jQuery Selector的执行流程以及书写性能--圈圈36期

Alibaba.com

May 20, 2013
Tweet

More Decks by Alibaba.com

Other Decks in Technology

Transcript

  1. JQuery和Sizzle的关系 Jquery 1.9中: jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"]

    = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains;
  2. $(Seletor)工作原理 $(selector, context),有以下类 型: ¡  Null ¡  DOMElement ¡  String

    ¡  Function ¡  JQuery Object ¡  Array selector Array Null DOM String Function Jquery Object
  3. JQuery和Sizzle连接 ¡  The work flow for $().find and $().filter: $().find:

    $().filter: For $(“selector”), it will use $().find $().find $.find Sizzle Sizzle.find Sizzle.filter $().filter $.multiFilter Sizzle.matches Sizzle Sizzle.filter
  4. Sizzle工作原理 Include below methods: ¡  Sizzle.find: it will be invoke

    one time. ¡  Sizzle.filter: it may be invoke many times. PS: The sizzle engine is base on regular expression, so we will see various regexp in source code. Sizzle Sizzle.find Sizzle.filter
  5. Sizzle工作原理 Excute regular expression chunker 1. It will transfer the

    selector to simple selectors which is array. 2. Divide the selector with char ‘,’ . For example: $(“div p, span p”) Sizzle Chunke r Span p div p
  6. Sizzle工作原理 ¡  origPOS = /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*) \))?(?=[^-]|$)/ If selector match origPOS,

    for example $(“div:eq(1) p”) Sizzle.find Sizzle.filter Sizzle.find div:eq(1) p :eq (1)
  7. Sizzle工作原理(Sizzle.find) ID • Match ID && context.getElementById Class • Match class &&

    context.getElementsByClassName Nam e • Match name && context.getElementsByName Tag • Match tag && context.getElementsByTagName * • Not match above || the results is null in above process How does $(“div.class1”) work in IE and Firefox?
  8. Sizzle工作原理(Sizzle.filter) ¡  Sizzle.filter( expr, set ) ¡  Type: PSEUDO, CHILD,

    ID, TAG, CLASS, ATTR, POS ¡  Regular expression: Expr.match ¡  Pre function: Expr.preFilter ¡  Function: Expr.filter
  9. 新改进 1.  词法分析器 l  解析逗号 l  Token : >, +,

    空格, ~ l  遍历正则数组 2.  Cache功能,selector作为key,解析后的group为value,注 意cache的是词法分析器的结果。
  10. Seajs解析流程 如图的加载过程: Load a1 -> judge a1 status a1 b1

    b2 Load a1 Fetch a1 Excute callback Load b1 Load b2
  11. 几种解析流程 1.  Seajs标准流程 2.  Atom优化流程 3.  尝试另一种思路, 先load叶子节点 Load a1

    Load b1 Load b2 Load b3 Load c1 Load c2 Load c3 Load d1 Load d2 Load a1 Load b1, Load b2, Load b3, Load c1, Load c2, Load c3, Load d1, Load d2 Load a1 Load c1, Load d1, Load d2, Load c3 Load c2, Load b1, Load b2, Load b3