Created
April 26, 2020 16:03
-
-
Save send2moran/964adb80f318b6b14d8d5091e06ef430 to your computer and use it in GitHub Desktop.
debounce MutationObserver
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 debounce = (func, delay) => { | |
let debounceTimer; | |
return function() { | |
const context = this; | |
const args = arguments; | |
clearTimeout(debounceTimer); | |
debounceTimer = setTimeout(() => func.apply(context, args), delay); | |
}; | |
}; | |
let summery = { addded: [], removed: [] }; | |
const send = debounce(() => console.log(`sending to server mutations: ${JSON.stringify({added: summery.addded, removed: summery.removed})}`),3000); | |
const log = mutations => { | |
for (let mutation of mutations) { | |
for (let node of mutation.addedNodes) { | |
// we track only elements, skip other nodes (e.g. text nodes) | |
if (!(node instanceof HTMLElement)) continue; | |
//console.log(node); | |
summery = { | |
...summery, | |
addded: [...summery.addded, node.outerHTML] | |
}; | |
} | |
for (let node of mutation.removedNodes) { | |
// we track only elements, skip other nodes (e.g. text nodes) | |
if (!(node instanceof HTMLElement)) continue; | |
summery = { | |
...summery, | |
removed: [...summery.removed, node.outerHTML] | |
}; | |
} | |
} | |
send(); | |
}; | |
let observer = new MutationObserver(log); | |
observer.observe(document.body, { childList: true, subtree: true }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment