源碼解析——FastClick

前些日子在做移動端的開發(fā)策添,早就聽聞移動端有300ms點擊延遲這一個問題恋捆,于是上找?guī)旖鉀Q棵逊。出于好奇心拜讀了一下FastClick庫的源碼,終于搞明白他解決問題的原理悼吱。

本文只做代碼解析慎框,如果對為什么有延遲等有疑問可以看一下我的另一篇文章 http://www.reibang.com/p/9cca518fa87b

1.FastClick解決的問題

移除移動端點擊(click)事件300ms的延遲

2.FastClick結(jié)構(gòu)

源碼是一個單js文件,一共800+的行數(shù)后添,支持amd笨枯,cmd和script直接引入。

;(function () {
  // FastClick 構(gòu)造函數(shù) 用來初始化并進(jìn)行事件綁定
  function FastClick(layer, options){……}
  // 一些判斷瀏覽器環(huán)境的代碼
  ……
  // 為FastClick類添加各種原型方法
  // 判斷是否需要原生點擊
  FastClick.prototype.needsClick = function(target) {……}
  // 判斷是否需要聚焦
  FastClick.prototype.needsFocus = function(target){……}
  // 向具體元素發(fā)送點擊事件
  FastClick.prototype.sendClick = function(targetElement, event){……}
  // 決定事件類型
  FastClick.prototype.determineEventType = function(targetElement){……}
  // 檢查目標(biāo)是否是滾動元素的子元素
  FastClick.prototype.updateScrollParent = function(targetElement){……}
  // 獲取點擊作用的目標(biāo)
  FastClick.prototype.updateScrollParent = function(targetElement){……}
  // 為觸摸事件綁定回調(diào)函數(shù)
  FastClick.prototype.onTouchStart = function(event){……}
  FastClick.prototype.touchHasMoved = function(event){……}
  FastClick.prototype.onTouchMove = function(event){……}
  FastClick.prototype.onTouchEnd = function(event){……}
  FastClick.prototype.onTouchCancel = function(){……}
  // 獲取label對應(yīng)的表單
  FastClick.prototype.findControl = function(labelElement){……}
  // 為未能取消的事件加保險
  FastClick.prototype.onMouse = function(event){……}
  // 點擊事件回調(diào)函數(shù)
  FastClick.prototype.onClick = function(event){……}
  // 移除所有回調(diào)函數(shù)
  FastClick.prototype.destroy = function(){……}
  // 判斷是否需要FastClick
  FastClick.notNeeded = function(layer){……}
  // 靜態(tài)工廠方法 暴露接口供使用者調(diào)用
  FastClick.attach = function(layer, options){……}
  // 模塊加載適配
  if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
        // AMD. Register as an anonymous module.
        define(function() {
            return FastClick;
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = FastClick.attach;
        module.exports.FastClick = FastClick;
    } else {
        window.FastClick = FastClick;
    }
})()

可以看出遇西,F(xiàn)astClick的源代碼的結(jié)構(gòu)是非常清晰的馅精。定義了一個FastClick的構(gòu)造函數(shù),為其原型添加共用的方法粱檀,之后添加了靜態(tài)方法洲敢。我們接下來一步一步來剖析源碼。

3.源碼解析

從官網(wǎng)的說明來看茄蚯,我們需要這樣在項目中引入FastClick

if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', function() {
        FastClick.attach(document.body);
    }, false);
}

那么我們的入口就是FastClick.attach這個函數(shù)

FastClick.attach = function(layer, options) {
    return new FastClick(layer, options);
};

可以看出這個靜態(tài)方法就是一個工廠函數(shù)压彭,用來創(chuàng)建并返回一個FastClick實例,自然我們看一下FastClick這個構(gòu)造函數(shù)渗常。

function FastClick(layer, options) {
        var oldOnClick;
        // 一些參數(shù)的定義
        options = options || {};

        /**
         * Whether a click is currently being tracked.
         *
         * @type boolean
         */
        this.trackingClick = false;


        /**
         * Timestamp for when click tracking started.
         *
         * @type number
         */
        this.trackingClickStart = 0;


        /**
         * The element being tracked for a click.
         *
         * @type EventTarget
         */
        this.targetElement = null;


        /**
         * X-coordinate of touch start event.
         *
         * @type number
         */
        this.touchStartX = 0;


        /**
         * Y-coordinate of touch start event.
         *
         * @type number
         */
        this.touchStartY = 0;


        /**
         * ID of the last touch, retrieved from Touch.identifier.
         *
         * @type number
         */
        this.lastTouchIdentifier = 0;

        /**
         * Touchmove boundary, beyond which a click will be cancelled.
         *
         * @type number
         */
        this.touchBoundary = options.touchBoundary || 10;


        /**
         * The FastClick layer.
         *
         * @type Element
         */
        this.layer = layer;

        /**
         * The minimum time between tap(touchstart and touchend) events
         *
         * @type number
         */
        this.tapDelay = options.tapDelay || 200;

        /**
         * The maximum time for a tap
         *
         * @type number
         */
        this.tapTimeout = options.tapTimeout || 700;

        if (FastClick.notNeeded(layer)) {
            return;
        }

        // Some old versions of Android don't have Function.prototype.bind
        function bind(method, context) {
            return function() { return method.apply(context, arguments); };
        }
        //  為函數(shù)綁定上下文
        var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
        var context = this;
        for (var i = 0, l = methods.length; i < l; i++) {
            context[methods[i]] = bind(context[methods[i]], context);
        }

        // Set up event handlers as required
        if (deviceIsAndroid) {
            layer.addEventListener('mouseover', this.onMouse, true);
            layer.addEventListener('mousedown', this.onMouse, true);
            layer.addEventListener('mouseup', this.onMouse, true);
        }
        // 綁定回調(diào)事件
        layer.addEventListener('click', this.onClick, true);
        layer.addEventListener('touchstart', this.onTouchStart, false);
        layer.addEventListener('touchmove', this.onTouchMove, false);
        layer.addEventListener('touchend', this.onTouchEnd, false);
        layer.addEventListener('touchcancel', this.onTouchCancel, false);

        // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
        // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
        // layer when they are cancelled.
        // 對stopImmediatePropagation做polyfill
        if (!Event.prototype.stopImmediatePropagation) {                               
            layer.removeEventListener = function(type, callback, capture) {
                var rmv = Node.prototype.removeEventListener;
                if (type === 'click') {
                    rmv.call(layer, type, callback.hijacked || callback, capture);
                } else {
                    rmv.call(layer, type, callback, capture);
                }
            };

            layer.addEventListener = function(type, callback, capture) {
                var adv = Node.prototype.addEventListener;
                if (type === 'click') {
                    adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
                        if (!event.propagationStopped) {
                            callback(event);
                        }
                    }), capture);
                } else {
                    adv.call(layer, type, callback, capture);
                }
            };
        }

        // If a handler is already declared in the element's onclick attribute, it will be fired before
        // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
        // adding it as listener.
        if (typeof layer.onclick === 'function') {

            // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
            // - the old one won't work if passed to addEventListener directly.
            oldOnClick = layer.onclick;
            layer.addEventListener('click', function(event) {
                oldOnClick(event);
            }, false);
            layer.onclick = null;
        }
    }

看懂代碼并不難壮不,主要過程就是
1.定義了一些我們之后操作需要用到的變量,同時進(jìn)行瀏覽器判斷是否需要FastClick來支持取消300ms的延遲(因為有些設(shè)置天然沒有皱碘,可以移步我開頭的文章询一,在這里我不詳細(xì)說明了)
2.為事件的回調(diào)函數(shù)綁定了FastClick實例
3.為點擊和觸摸事件綁定回調(diào)函數(shù)(最重要的一步)
4.為stopImmediatePropagation做polyfill
也就是說,通過創(chuàng)建實例來為傳入的layer綁定回調(diào)事件來解決問題。下面一一來解析每個事件的回調(diào)函數(shù)

  • touchstart
FastClick.prototype.onTouchStart = function(event) {
        var targetElement, touch, selection;

        if (event.targetTouches.length > 1) {
            return true;
        }

        targetElement = this.getTargetElementFromEventTarget(event.target);

        touch = event.targetTouches[0];
        // 對ios做一些兼容性處理
        if (deviceIsIOS) {
            selection = window.getSelection();
            // 處理是否為長按選中 
            if (selection.rangeCount && !selection.isCollapsed) {
                return true;
            }

            if (!deviceIsIOS4) {
                if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
                    event.preventDefault();
                    return false;
                }

                this.lastTouchIdentifier = touch.identifier;
                this.updateScrollParent(targetElement);
            }
        }
        //  追蹤這個點擊事件并記錄一些信息
        this.trackingClick = true;
        this.trackingClickStart = event.timeStamp;
        this.targetElement = targetElement;

        this.touchStartX = touch.pageX;
        this.touchStartY = touch.pageY;
        // 如果兩次點擊時間差小于預(yù)設(shè)的時間差 則取消第二次點擊
        if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
            event.preventDefault();
        }

        return true;
    };

在onTouchStart中我們主要記錄了這次點擊的一些信息健蕊,包括時間缓醋、位置、點擊作用的元素绊诲。并處理了快速的雙擊要取消第二次點擊的問題。

tips: 在touch事件中調(diào)用event.preventDefault() 是可以取消觸發(fā)原生的click事件的 同理作用于focus事件 mouseup等褪贵。這也正是FastClick的原理之一掂之。

  • touchmove
FastClick.prototype.onTouchMove = function(event) {
        if (!this.trackingClick) {
            return true;
        }

        // If the touch has moved, cancel the click tracking
        if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
            this.trackingClick = false;
            this.targetElement = null;
        }

        return true;
    };

onTouchMove主要是用來區(qū)分是否是一個點擊還是滑動,如果是滑動就取消追蹤這個click

  • touchend
FastClick.prototype.onTouchEnd = function(event) {
        var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
        // 如果不存在追蹤click直接返回
        if (!this.trackingClick) {
            return true;
        }
        // 取消第二次延遲 
        if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
            this.cancelNextClick = true;
            return true;
        }
        // touchend于touchstart的時間差太長應(yīng)為選擇事件
        if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
            return true;
        }

        this.cancelNextClick = false;

        this.lastClickTime = event.timeStamp;

        trackingClickStart = this.trackingClickStart;
        this.trackingClick = false;
        this.trackingClickStart = 0;

        if (deviceIsIOSWithBadTarget) {
            touch = event.changedTouches[0];

            targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
            targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
        }

        targetTagName = targetElement.tagName.toLowerCase();
        // ******重點******
        // 如果點擊的是一個label 則需要聚焦到label for的元素
        if (targetTagName === 'label') {
            forElement = this.findControl(targetElement);
            if (forElement) {
                this.focus(targetElement);
                if (deviceIsAndroid) {
                    return false;
                }

                targetElement = forElement;
            }
        } else if (this.needsFocus(targetElement)) {
            // 如果是一個需要focus的元素脆丁,則聚焦他并模擬一個點擊事件
            if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
                this.targetElement = null;
                return false;
            }
            
            this.focus(targetElement);
            this.sendClick(targetElement, event);

            if (!deviceIsIOS || targetTagName !== 'select') {
                this.targetElement = null;
                event.preventDefault();
            }

            return false;
        }

        if (deviceIsIOS && !deviceIsIOS4) {
            scrollParent = targetElement.fastClickScrollParent;
            if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
                return true;
            }
        }
        // 如果元素需要點擊事件 則阻止原生點擊 并模擬一個點擊事件
        if (!this.needsClick(targetElement)) {
            event.preventDefault();
            this.sendClick(targetElement, event);
        }

        return false;
    };

這里正是FastClick的精髓世舰,取消原生點擊事件并立馬模擬一個點擊事件來取消這300ms的延遲。
再來看這兩個關(guān)鍵函數(shù)

FastClick.prototype.focus = function(targetElement) {
        var length;
        if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month' && targetElement.type !== 'email') {
            length = targetElement.value.length;
            targetElement.setSelectionRange(length, length);
        } else {
            targetElement.focus();
        }
    };

聚焦元素會調(diào)用原生的focus事件槽卫,但是這里面還是有一個小bug的跟压,每次點擊觸發(fā)的時候這個focus的時候,在ios設(shè)備上會選擇到已輸入字符的最后歼培,也就不是自己點擊的那個位置震蒋。

    FastClick.prototype.sendClick = function(targetElement, event) {
        var clickEvent, touch;

        // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
        if (document.activeElement && document.activeElement !== targetElement) {
            document.activeElement.blur();
        }

        touch = event.changedTouches[0];

        // Synthesise a click event, with an extra attribute so it can be tracked
        clickEvent = document.createEvent('MouseEvents');
        clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
        clickEvent.forwardedTouchEvent = true;
        targetElement.dispatchEvent(clickEvent);
    };

使用原生的方法模擬一個鼠標(biāo)事件,并且通過dispatchEvent方法觸發(fā)這個事件躲庄。

  • touchcancel
    FastClick.prototype.onTouchCancel = function() {
        this.trackingClick = false;
        this.targetElement = null;
    };

onTouchCancel只是取消了追蹤

  • click
FastClick.prototype.onClick = function(event) {
        var permitted;

        if (this.trackingClick) {
            this.targetElement = null;
            this.trackingClick = false;
            return true;
        }

        if (event.target.type === 'submit' && event.detail === 0) {
            return true;
        }

        permitted = this.onMouse(event);

        if (!permitted) {
            this.targetElement = null;
        }

        return permitted;
    };

主要是針對于捕捉的點擊事件使用prevent并沒有取消掉原生點擊事件的問題

  • mouse
FastClick.prototype.onMouse = function(event) {
        if (!this.targetElement) {
            return true;
        }

        if (event.forwardedTouchEvent) {
            return true;
        }

        if (!event.cancelable) {
            return true;
        }
        if (!this.needsClick(this.targetElement) || this.cancelNextClick) {

            // Prevent any user-added listeners declared on FastClick element from being fired.
            if (event.stopImmediatePropagation) {
                event.stopImmediatePropagation();
            } else {

                // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
                event.propagationStopped = true;
            }

            // Cancel the event
            event.stopPropagation();
            event.preventDefault();

            return false;
        }
        return true;
    };

主要是理解一下stopImmediatePropagation這個方法查剖,會阻止其相同層次綁定的其他事件的發(fā)生。

4.總結(jié)

源碼中還有其他的一些函數(shù)噪窘,有興趣可以自行翻閱一下笋庄,整體比較重要部分的分析已經(jīng)寫明了,其中對于各種兼容處理的代碼并沒有說明倔监,感覺也并不是特別的重要直砂,畢竟現(xiàn)在也沒人去支持android2 3了吧,有興趣也可以去讀一讀(畢竟沒有設(shè)備也看不了效果昂葡啊)
源碼還是挺好讀懂的静暂,也學(xué)到了關(guān)于移動端事件的一些知識,對于模擬事件并觸發(fā)的機制也搞懂了瘦锹,感覺收獲還是挺大的籍嘹,(雖然這個庫現(xiàn)在用處也不是很大了,具體原因在文章頭部的那篇文章里有寫)
————————————————————————————
下一個目標(biāo):Axios(請求庫)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末弯院,一起剝皮案震驚了整個濱河市辱士,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌听绳,老刑警劉巖颂碘,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡头岔,警方通過查閱死者的電腦和手機塔拳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來峡竣,“玉大人靠抑,你說我怎么就攤上這事∈赎” “怎么了颂碧?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長类浪。 經(jīng)常有香客問我载城,道長,這世上最難降的妖魔是什么费就? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任诉瓦,我火速辦了婚禮,結(jié)果婚禮上力细,老公的妹妹穿的比我還像新娘睬澡。我一直安慰自己,他們只是感情好眠蚂,可當(dāng)我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布猴贰。 她就那樣靜靜地躺著,像睡著了一般河狐。 火紅的嫁衣襯著肌膚如雪米绕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天馋艺,我揣著相機與錄音栅干,去河邊找鬼。 笑死捐祠,一個胖子當(dāng)著我的面吹牛碱鳞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播踱蛀,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼窿给,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了率拒?” 一聲冷哼從身側(cè)響起崩泡,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎猬膨,沒想到半個月后角撞,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年谒所,在試婚紗的時候發(fā)現(xiàn)自己被綠了热康。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡劣领,死狀恐怖姐军,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情尖淘,我是刑警寧澤庶弃,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站德澈,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏固惯。R本人自食惡果不足惜梆造,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望葬毫。 院中可真熱鬧镇辉,春花似錦、人聲如沸贴捡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽烂斋。三九已至屹逛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間汛骂,已是汗流浹背罕模。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留帘瞭,地道東北人淑掌。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像蝶念,于是被迫代替她去往敵國和親抛腕。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 以前聽到前輩們說移動端盡量不要使用click媒殉,click會比較遲鈍担敌,能用touchstart還是用touchsta...
    極樂君閱讀 654評論 0 2
  • 1.幾種基本數(shù)據(jù)類型?復(fù)雜數(shù)據(jù)類型?值類型和引用數(shù)據(jù)類型?堆棧數(shù)據(jù)結(jié)構(gòu)? 基本數(shù)據(jù)類型:Undefined、Nul...
    極樂君閱讀 5,514評論 0 106
  • 相關(guān)知識點 移動端廷蓉、 適配(兼容)柄错、 ios點擊事件300ms延遲、 點擊穿透、 定位失效...... 問題&解決...
    sandisen閱讀 25,491評論 3 67
  • 女孩在工作的飯店里喜歡上了一個廚師售貌,女孩不善言辭给猾,一天他和她說話了,女孩高興了一整天颂跨,直到有一天女孩鼓起勇氣...
    快樂的大白兔閱讀 153評論 0 0
  • 最近被一連串的事情弄得生活節(jié)奏實在是有些些的緊張恒削。 起初是因為所租住的住所即將到期池颈,而一直猶豫于是否立刻開始尋租,...
    小宇宙_cw閱讀 288評論 0 0