jQuery2.0.3源码分析

总体架构

// 匿名子执行函数
(function() {
    (21,94) 定义一些变量和函数 jQuery = function() {};
    (96,283) 给jq对象,添加属性和方法,
    (285, 347) extend: jQ的继承方法
    (349, 817) jQuery.extend(): 拓展一些工具方法,静态
    (877,2856) Sizzle : 复杂选择器的实现
    (2880,3042) Callbacks: 回调对象:函数的统一管理
    (3043,3183) Deferred: 延迟对象: 对异步的统一管理
    (3184,3295) support :功能检测
    (3308, 3652) data() : 数据缓存
    (3653, 3797) queue(): 队列管理 保证异步的执行顺序
    (3803,4299) attr() prop() val() addClass() 对元素的操作
    (4300, 5128) on() prop() val() addClass() 对元素的操作
    (5140, 6057) DOM操作: 添加 删除 获取 包装 DOM 筛选
    (6058,6620) css() 样式的操作
    (6621,7854) 提交的数据和ajax(): ajax() load() getJson()
    (7855,8584) animate()
    (8585,8792) offset() : 位置和尺寸的方法 
    (8804,8821) JQ支持模块化的模式
})()
  • rootJquery 所有jq对象最后返回这些?
  • readyList 与DOM加载相关
  • core_strundedfined = typeof undefined

兼容处理,老版浏览器无法使用'undefined'判断XML中string类型

  • location、document、docElem
  • jQuery = window.jQuery, $ = window.$,防止被重写
  • class2type 用于类型判断,用json格式保存多种类型值
_$ = window.$,
  • _$ = window.$,
  • core_version = "2.0.3", 版本号 // _proto_的jquery属性
  • core_pnum = // ; 数字的正则,与css表达式相关
rootjQuery = jQuery(document);

completed

completed = function() {
        document.removeEventListener( "DOMContentLoaded", completed, false );
        window.removeEventListener( "load", completed, false );
        jQuery.ready();
    };

注:DOMContentLoaded与onload区别

1.当onload事件触发时,页面上所有的DOM,样式表,脚本,图片flash都加载完
2.当DOMContentLoaded事件触发时,仅当DOM加载完成时,不包括样式表,图片,flash

jQuery.fn 代替 jQuery.prototype

jQuery.fn = jQuery.prototype = {
    constructor: jQuery,  // 指定constructor
}

jQuery.fn.init(selector,context,rootJquery)

if (selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3) 
// <html> <html>...</html>

else //<html>ddd

if( match && (match[1] || !context) ) // html标签
    if(match[1]) // html标签
        // 匹配单标签
        if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) )
else //#id
  • parseHtml(str,docment,false)把字符串转为节点数组

context 指定不同环境下的根节点

参数selector,接受任何类型的值

  • "" , null, undefined, false的处理,返回原值
if ( !selector ) {
    return this;
}

this指空jQuery对象

处理HTML字符串

parseHTML: function( data, context, keepScripts ) {
        if ( !data || typeof data !== "string" ) {
            return null;
        }
        if ( typeof context === "boolean" ) {
            keepScripts = context;
            context = false;
        }
        context = context || document;

        var parsed = rsingleTag.exec( data ),
            scripts = !keepScripts && [];

        // Single tag
        if ( parsed ) {
            return [ context.createElement( parsed[1] ) ];
        }

        parsed = jQuery.buildFragment( [ data ], context, scripts );

        if ( scripts ) {
            jQuery( scripts ).remove();
        }

        return jQuery.merge( [], parsed.childNodes );
    }

参数类型判断必不可少,这也是js这门语言带来的头痛的问题之一。

相关推荐