Created
November 19, 2023 12:06
-
-
Save duncansmart/b970e0e0b6cf9e82ad3d553afa4a62ac to your computer and use it in GitHub Desktop.
Call initFunc on elements in selector that are in DOM now and also on dynamically-added elements later on
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
// Call initFunc on elements in selector that are in DOM now and also on dynamically-added elements later on | |
function dynamicInit(selector, initFunc) { | |
//console.log('dynamicInit', selector) | |
window._dynamicInitData ??= []; | |
window._dynamicInitData.push({ selector, initFunc }); | |
if (!window._dynamicInitObserver) { | |
window._dynamicInitObserver = new MutationObserver(function (mutations) { | |
// avoid infinite loop when we add new elements below | |
window._dynamicInitObserver.disconnect() | |
for (let mutation of mutations) { | |
for (let addedNode of mutation.addedNodes) { | |
if (addedNode.nodeName != '#text' && addedNode.nodeName != '#comment') { | |
//console.log(' ... dynamicInit', addedNode) | |
window._dynamicInitData.forEach(function (item) { | |
//console.log(' ... dynamicInit', item.selector) | |
// short-circuit if selector not found | |
if (!addedNode.querySelector(item.selector)) | |
return; | |
addedNode.querySelectorAll(item.selector).forEach(function (el) { | |
//console.log(' ... dynamicInit', item.selector, el) | |
if (!el.dataset['dynamicinit']) { | |
//console.log('dynamically init-ing', item.selector, el) | |
item.initFunc.apply(el) | |
} | |
el.dataset['dynamicinit'] = 1 | |
}) | |
}); | |
} | |
} | |
} | |
// re-observe | |
window._dynamicInitObserver.observe(document, { childList: true, subtree: true }) | |
}) | |
// start observing | |
window._dynamicInitObserver.observe(document, { childList: true, subtree: true }) | |
} | |
// initial init | |
document.querySelectorAll(selector).forEach(function (el) { | |
if (!el.dataset['dynamicinit']) | |
initFunc.apply(el) | |
el.dataset['dynamicinit'] = 1 | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment