9

我正在开发一个 JavaScript 模块,它对将在其中使用它的环境一无所知。

而且,从技术上讲,我想实现下一个功能:

onceAppended(element, callback);

element是一个HTMLElement并且这个元素的父元素在模块初始化期间可能是未知的。是一个函数,一旦出现在页面上就callback必须触发。element

如果元素附加到文档,则必须立即调用回调。如果element尚未附加,则功能将在文档上出现时callback触发。element

问题是,我们可以element使用DOMNodeInserted突变事件来检测附加事件。但突变事件现在已被弃用。而且似乎MutationObserver无法处理这个任务,可以吗?

这是我的代码片段:

function onceAppended (element, callback) {
    let el = element,
        listener;
    while (el.parentNode)
        el = el.parentNode;
    if (el instanceof Document) {
        callback();
        return;
    }
    if (typeof MutationObserver === "undefined") { // use deprecated method
        element.addEventListener("DOMNodeInserted", listener = (ev) => {
            if (ev.path.length > 1 && ev.path[ev.length - 2] instanceof Document) {
                element.removeEventListener("DOMNodeInserted", listener);
                callback();
            }
        }, false);
        return;
    }
    // Can't MutationObserver detect append event for the case?
}
4

2 回答 2

2

不幸的是,没有办法以与 with 完全相同的方式执行此操作,DOMNodeInserted因为没有任何MutationObserver事件会告诉您元素的parent 何时更改

相反,您必须将观察者放在document.body并检查每个附加的节点。如果您想在附加任何节点时运行回调,那很容易。如果您只希望它在附加某些节点时运行,那么您必须在某处保留对这些节点的引用。

let elements = [];
elements[0] = document.createElement('div');
elements[1] = document.createElement('span');
elements[2] = document.createElement('p');
elements[3] = document.createElement('a');

const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

const observer = new MutationObserver(function(mutations) {
  // 'addedNodes' is an array of nodes that were appended to the DOM.
  // Checking its length let's us know if we've observed a node being added
  if (mutations[0].addedNodes.length > 0) {

    // 'indexOf' let's us know if the added node is in our reference array
    if (Array.prototype.indexOf.call(mutations[0].addedNodes[0], elements) > -1) {

      // Run the callback function with a reference to the element
      callback(mutations[0].addedNodes[0]);
    }
});

observer.observe(document.body, {
  childList: true,
  subtree: true
});

function callback(element) {
  console.log(element);
}

document.body.appendChild(elements[2]); // => '<p></p>'
elements[2].appendChild(elements[3]);   // => '<a></a>'

如您所见,回调是针对附加在document.body. 如果您想callback()在添加任何元素时运行,只需第二次检查该元素是否存在于您的参考数组中。

于 2016-07-26T14:26:08.287 回答
1

通过 wOxxOm 对 DOMNodeInserted 的替代方案的提示和 skyline3000 的回答,我开发了此任务解决方案的两种方法。第一种方法速度很快,但在触发onceAppended之前它有大约 25 毫秒的延迟。callback第二种方法callback在插入元素后立即触发,但是当应用程序中追加大量元素时,它可能会很慢。

该解决方案可在GitHub 上npm ES6模块的形式获得。以下是两种解决方案的纯代码。

方法一(使用 CSS 动画)

function useDeprecatedMethod (element, callback) {
    let listener;
    return element.addEventListener(`DOMNodeInserted`, listener = (ev) => {
        if (ev.path.length > 1 && ev.path[ev.length - 2] instanceof Document) {
            element.removeEventListener(`DOMNodeInserted`, listener);
            callback();
        }
    }, false);
}

function isAppended (element) {
    while (element.parentNode)
        element = element.parentNode;
    return element instanceof Document;
}

/**
 * Method 1. Asynchronous. Has a better performance but also has an one-frame delay after element is
 * appended (around 25ms delay) of callback triggering.
 * This method is based on CSS3 animations and animationstart event handling.
 * Fires callback once element is appended to the document.
 * @author ZitRo (https://github.com/ZitRos)
 * @see https://stackoverflow.com/questions/38588741/having-a-reference-to-an-element-how-to-detect-once-it-appended-to-the-document (StackOverflow original question)
 * @see https://github.com/ZitRos/dom-onceAppended (Home repository)
 * @see https://www.npmjs.com/package/dom-once-appended (npm package)
 * @param {HTMLElement} element - Element to be appended
 * @param {function} callback - Append event handler
 */
export function onceAppended (element, callback) {

    if (isAppended(element)) {
        callback();
        return;
    }

    let sName = `animation`, pName = ``;

    if ( // since DOMNodeInserted event is deprecated, we will try to avoid using it
        typeof element.style[sName] === `undefined`
        && (sName = `webkitAnimation`) && (pName = "-webkit-")
            && typeof element.style[sName] === `undefined`
        && (sName = `mozAnimation`) && (pName = "-moz-")
            && typeof element.style[sName] === `undefined`
        && (sName = `oAnimation`) && (pName = "-o-")
            && typeof element.style[sName] === `undefined`
    ) {
        return useDeprecatedMethod(element, callback);
    }

    if (!document.__ONCE_APPENDED) {
        document.__ONCE_APPENDED = document.createElement('style');
        document.__ONCE_APPENDED.textContent = `@${ pName }keyframes ONCE_APPENDED{from{}to{}}`;
        document.head.appendChild(document.__ONCE_APPENDED);
    }

    let oldAnimation = element.style[sName];
    element.style[sName] = `ONCE_APPENDED`;
    element.addEventListener(`animationstart`, () => {
        element.style[sName] = oldAnimation;
        callback();
    }, true);

}

方法2(使用MutationObserver)

function useDeprecatedMethod (element, callback) {
    let listener;
    return element.addEventListener(`DOMNodeInserted`, listener = (ev) => {
        if (ev.path.length > 1 && ev.path[ev.length - 2] instanceof Document) {
            element.removeEventListener(`DOMNodeInserted`, listener);
            callback();
        }
    }, false);
}

function isAppended (element) {
    while (element.parentNode)
        element = element.parentNode;
    return element instanceof Document;
}

/**
 * Method 2. Synchronous. Has a lower performance for pages with a lot of elements being inserted,
 * but triggers callback immediately after element insert.
 * This method is based on MutationObserver.
 * Fires callback once element is appended to the document.
 * @author ZitRo (https://github.com/ZitRos)
 * @see https://stackoverflow.com/questions/38588741/having-a-reference-to-an-element-how-to-detect-once-it-appended-to-the-document (StackOverflow original question)
 * @see https://github.com/ZitRos/dom-onceAppended (Home repository)
 * @see https://www.npmjs.com/package/dom-once-appended (npm package)
 * @param {HTMLElement} element - Element to be appended
 * @param {function} callback - Append event handler
 */
export function onceAppendedSync (element, callback) {

    if (isAppended(element)) {
        callback();
        return;
    }

    const MutationObserver =
        window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

    if (!MutationObserver)
        return useDeprecatedMethod(element, callback);

    const observer = new MutationObserver((mutations) => {
        if (mutations[0].addedNodes.length === 0)
            return;
        if (Array.prototype.indexOf.call(mutations[0].addedNodes, element) === -1)
            return;
        observer.disconnect();
        callback();
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

}

这两种方法的用法相同,只是函数名不同:

import { onceAppended } from "dom-once-appended"; // or onceAppendedSync

function myModule () {
    let sampleElement = document.createElement("div");
    onceAppended(sampleElement, () => { // or onceAppendedSync
        console.log(`Sample element is appended!`);
    });
    return sampleElement;
}

// somewhere else in the sources (example)
let element = myModule();
setTimeout(() => document.body.appendChild(element), 200);
于 2016-07-28T12:22:19.337 回答