onDomChange

Dom变化监听

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/464529/1183888/onDomChange.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         onDomChange
// @namespace    http://bbs.91wc.net/?onDomChange
// @version      0.1.2
// @description  Dom变化监听
// @author       Wilson
// ==/UserScript==
 
function onDomChange(el, callback, config) {
    // 观察器的配置(需要观察什么变动)
    config = config || { attributes: true, childList: true, subtree: true };
    // 当观察到变动时执行的回调函数
    const handler = function(mutationsList, observer) {
        // Use traditional 'for loops' for IE 11
        for(let mutation of mutationsList) {
            callback(observer, mutation);
        }
    };
    // 创建一个观察器实例并传入回调函数
    const observer = new MutationObserver(handler);

    // 以上述配置开始观察目标节点
    el = typeof el === 'string' ? document.querySelector(el) : el;
    observer.observe(el, config);

    //再次开始观察,通常用于先停止监听处理后再监听的场景,防止死循环
    observer.observeAgain = function(ele, cfg){
        observer.observe(ele || el, cfg || config);
    }

    // 之后,可停止观察
    //observer.disconnect();

    return observer;
}

//使用示例:
//说明:childList是子元素,subtree是后代元素
//onDomChange(el, (observer, mutation) => {
    //your code

    //if (mutation.type === 'childList'){
        //do something
    //}
    //if(observer) observer.disconnect();
    //observer.observeAgain();
//}, {childList: true});