protyle 加载时执行

protyle加载时执行

注意这个是开始加载时,不是加载完成

这种方式实现,如果是添加导航按钮等,不会出现闪烁,但如果是修改编辑器内容推荐 protyle加载完成

// 监听protyle加载,注意这个是开始加载时,不是加载完成
// 调用示例 observeProtyleLoad((protyle)=>console.log(protyle))
function observeProtyleLoad(callback, node) {
    let hasLoad = false;
    const observeCallback = (element) => {
        if(hasLoad) return;
        hasLoad = true;
        callback(element);
        setTimeout(()=>hasLoad=false, 200);
    };
  
    // 旧版本加载需要这个
    whenElementExist('.protyle:not(.fn__none)').then(observeCallback);
    // 监听加载protyle
    observeProtyleLoading(observeCallback, node);
}
function whenElementExist(selector, node) {
    return new Promise(resolve => {
        const check = () => {
            const el = typeof selector==='function'?selector():(node||document).querySelector(selector);
            if (el) resolve(el); else requestAnimationFrame(check);
        };
        check();
    });
}
function observeProtyleLoading(callback, parentElement) {
    // 如果 parentElement 是字符串,则将其转换为 DOM 元素
    if (typeof parentElement === 'string') {
        parentElement = document.querySelector(parentElement);
    }
    // 创建一个 MutationObserver 实例
    const observer = new MutationObserver((mutationsList) => {
        mutationsList.forEach((mutation) => {
            // 检查是否是属性变化并且变化的属性是 class
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                const targetElement = mutation.target; // 发生变化的目标元素

                // 判断目标元素是否匹配指定选择器 .protyle:not(.fn__none)
                if (targetElement.matches('.protyle:not(.fn__none)')) {
                    // 触发回调
                    callback(targetElement);
                }
            }
        });
    });
    // 配置观察选项
    const config = {
        attributes: true, // 监听属性变化
        attributeFilter: ['class'], // 仅监听 class 属性
        subtree: true, // 监听父容器及其所有后代元素
    };
    // 启动观察,默认监听 document.body 或指定的父容器
    observer.observe(parentElement || document.body, config);
}

相关 protyle加载完成

image.png

留下你的脚步
推荐阅读