Created
May 14, 2019 13:18
-
-
Save mafintosh/7b6ad391a79c4d187ae6c60af74dbb82 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tracking = new WeakMap() | |
const clz = 'onload-' + Math.random().toString(36).slice(2) | |
const observer = new MutationObserver(function (mutations) { | |
for (let j = 0; j < mutations.length; j++) { | |
const { addedNodes, removedNodes, target } = mutations[j] | |
for (let i = 0; i < addedNodes.length; i++) { | |
if (!addedNodes[i].classList) continue | |
if (addedNodes[i].classList.contains(clz)) tracking.get(addedNodes[i]).onload(target) | |
const els = addedNodes[i].getElementsByClassName(clz) | |
for (let k = 0; k < els.length; k++) tracking.get(els[k]).onload(target) | |
} | |
for (let i = 0; i < removedNodes.length; i++) { | |
if (!removedNodes[i].classList) continue | |
if (removedNodes[i].classList.contains(clz)) tracking.get(removedNodes[i]).offload(target) | |
const els = removedNodes[i].getElementsByClassName(clz) | |
for (let k = 0; k < els.length; k++) tracking.get(els[k]).offload(target) | |
} | |
} | |
}) | |
observer.observe(document, { | |
childList: true, | |
subtree: true, | |
}) | |
module.exports = function (node, onload, offload) { | |
node.classList.add(clz) | |
tracking.set(node, { onload, offload }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment