天天看點

一次DOM曝光封裝曆程

作者:閃念基因

随着最近曝光埋點的需求越來越頻繁,就想把之前寫好的曝光邏輯抽出來封裝了一下作為公用。

一次DOM曝光封裝曆程

初版

邏輯:window.scroll 監聽滾動 + 使用 getBoundingClientRect() 相對于視口位置實作

具體代碼如下:

function buryExposure (el, fn) {
    /*
    * 省略一些邊界判斷
    * ......
    **/
    let elEnter = false; // dom是否進入可視區域
    el.exposure = () => {
        const { top } = el.getBoundingClientRect();
        if (top > 0 && top < window.screen.availHeight) {
            if (!elEnter) {
                elEnter = true;
                fn(el)
            }
        } else {
            elEnter = false;
        };
    }
    document.addEventListener('scroll', el.exposure);
}
           

回調傳出 el ,一般為頁面登出時登出對應滾動事件: el.exposure

其中兩個點

第一個:

// 判斷上邊距出現在視口内,則判定為曝光
const { top } = el.getBoundingClientRect();
if (top > 0 && top < window.screen.availHeight)
           

其中這裡的 top 以及其他邊距對應視口計算方式可能和你想象的不一樣,上圖摘自 你真的會用getBoundingClientRect 嗎 (https://juejin.im/entry/59c1fd23f265da06594316a9), 它對這個屬性講的比較詳細可以看看

第二個:

let elEnter = false; //
           

用一個變量來控制當 dom 已經曝光則不再持續,直到 dom 離開視口,重新計算

重寫

當我以為已經夠用時,某次需求需要監聽 DOM 在某個 div 内橫向滑動的曝光,發現它并不支援!而後面一些曝光政策對比的文章說到這個 getBoundingClientRect API 會引起性能問題

不相信的你可以試一下!!!

于是我就開啟 google 大法和在掘金社群内搜一些曝光的文章,然後我就發現了新大陸!

window.IntersectionObserver

這次曝光的主角:優先使用異步觀察目标元素與祖先元素或頂級文檔viewport的交集中的變化的方法

關于他的具體介紹,我這裡簡單講一下我用到的屬性,具體可查閱 超好用的 API 之 IntersectionObserver (https://juejin.im/post/5d11ced1f265da1b7004b6f7) 或者 MDN (https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver)

主要使用如下:

const io = new IntersectionObserver(callback, options)
io.observe(DOM)
           
  • callback 回調函數,options 是配置參數
  • io.observe 觀察函數,DOM 為被觀察對象

主要兩點

1.options 的配置為:

const observerOptions = {
    root: null,  // 預設使用視口作為交集對象
    rootMargin: '0px', // 無樣式
    threshold: [...Array(100).keys()].map(x => x / 100) // 監聽交集時的每0.01變化觸發callback回調
}
           

2.callback 函數如下:

(entries) => {
    // 過程性監聽
    entries.forEach((item) => {
        if (item.intersectionRatio > 0 && item.intersectionRatio <= 1) { // 部分顯示即為顯示
            // todo....
        } else if (item.intersectionRatio === 0) { // 不可見時恢複
            // todo...
        }
    });
}
           

曝光的判斷來自以下第二種(部分顯示則曝光):

  • intersectionRatio === 1:則監聽對象完整顯示
  • intersectionRatio > 0 && intersectionRatio < 1 : 則監聽對象部分顯示
  • intersectionRatio === 0:則監聽對象不顯示其實 entries[] 子元素對象還有一個屬性:isIntersecting

傳回一個布爾值,下列兩種操作均會觸發 callback:

  1. 如果目标元素出現在 root 可視區,傳回 true。
  2. 如果從 root 可視區消失,傳回 false

按理說應該是使用它,但是發現不适合現實場景!!!

比如 類 banner 橫向移動 (https://jsbin.com/vuzujiw/6/edit?html,css,js,console,output),我第一調試的時候就碰到了

使用者要看的子元素是被父元素給限制住了,但是對于 isIntersecting 它來講是出現在視口内的。

最終版

考慮相容性:

// 使用w3c出的polyfill
require('intersection-observer');
           

主要邏輯如下:

/**
 * DOM曝光
 * @param {object} options 配置參數
 * options @param {Array} DOMs 要被監聽的DOM清單
 * options @param {Function} callback[type, io] 回調,傳入參數
 * options @param {DOM} parentDom 子元素的對應父元素
 */
export default function expose (options = {}) {
    if (!options.DOMs || !options.callback) {
        console.error('Error: 傳入監聽DOM或者回調函數');
        return;
    }
    const observerOptions = {
        root: null,
        rootMargin: '0px',
        threshold: [...Array(100).keys()].map(x => x / 100)
    };
    options.parentDom && (observerOptions.root = options.parentDom);
    // 優先使用異步觀察目标元素與祖先元素或頂級文檔viewport的交集中的變化的方法
    if (window.IntersectionObserver) {
        let elEnter = false; // dom是否進入可視區域
        const io = new IntersectionObserver((entries) => {
            // 回調包裝
            const fn = () => options.callback({ io });
            // 過程性監聽
            entries.forEach((item) => {
                if (!elEnter && item.intersectionRatio > 0 && item.intersectionRatio <= 1) { // 部分顯示即為顯示
                    fn();
                    elEnter = true;
                } else if (item.intersectionRatio === 0) { // 不可見時恢複
                    elEnter = false;
                }
            });
        }, observerOptions);
        // 監聽DOM
        options.DOMs.forEach(DOM => io.observe(DOM));
    }
}
           

參考文獻

你真的會用 getBoundingClientRect 嗎(https://juejin.im/entry/59c1fd23f265da06594316a9)

作者:開盛

來源:微信公衆号:政采雲技術

出處:https://mp.weixin.qq.com/s/oZKjlSiLiBgcT0TfZ1zMhw