Files

107 lines
2.8 KiB
JavaScript
Raw Permalink Normal View History

// Ported from on-load 3.4.1 (MIT) — https://github.com/shama/on-load
// Fire load/unload callbacks when watched nodes enter or leave the DOM,
// driven by a single document-wide MutationObserver.
const watch = Object.create(null)
const KEY_ID = 'onloadid' + Math.random().toString(36).slice(2, 8)
const KEY_ATTR = 'data-' + KEY_ID
let INDEX = 0
if (typeof window !== 'undefined' && window.MutationObserver) {
const observer = new window.MutationObserver(function (mutations) {
if (Object.keys(watch).length < 1) return
for (let i = 0; i < mutations.length; i++) {
if (mutations[i].attributeName === KEY_ATTR) {
eachAttr(mutations[i], turnon, turnoff)
continue
}
eachMutation(mutations[i].removedNodes, turnoff)
eachMutation(mutations[i].addedNodes, turnon)
}
})
if (document.body) {
beginObserve(observer)
} else {
document.addEventListener('DOMContentLoaded', function () {
beginObserve(observer)
})
}
}
function beginObserve (observer) {
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: true,
attributeFilter: [KEY_ATTR]
})
}
export default function onload (el, on, off, caller) {
if (!document.body) throw new Error('onload: will not work prior to DOMContentLoaded')
on = on || function () {}
off = off || function () {}
el.setAttribute(KEY_ATTR, 'o' + INDEX)
watch['o' + INDEX] = [on, off, 0, caller]
INDEX += 1
return el
}
onload.KEY_ATTR = KEY_ATTR
onload.KEY_ID = KEY_ID
export { KEY_ATTR, KEY_ID }
function turnon (index, el) {
if (watch[index][0] && watch[index][2] === 0) {
watch[index][0](el)
watch[index][2] = 1
}
}
function turnoff (index, el) {
if (watch[index][1] && watch[index][2] === 1) {
watch[index][1](el)
watch[index][2] = 0
}
}
function eachAttr (mutation, on, off) {
const newValue = mutation.target.getAttribute(KEY_ATTR)
if (sameOrigin(mutation.oldValue, newValue)) {
watch[newValue] = watch[mutation.oldValue]
return
}
if (watch[mutation.oldValue]) {
off(mutation.oldValue, mutation.target)
}
if (watch[newValue]) {
on(newValue, mutation.target)
}
}
function sameOrigin (oldValue, newValue) {
if (!oldValue || !newValue) return false
if (!watch[oldValue] || !watch[newValue]) return false
return watch[oldValue][3] === watch[newValue][3]
}
function eachMutation (nodes, fn) {
const keys = Object.keys(watch)
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]
if (node && node.getAttribute && node.getAttribute(KEY_ATTR)) {
const onloadid = node.getAttribute(KEY_ATTR)
keys.forEach(function (k) {
if (onloadid === k) {
fn(k, node)
}
})
}
if (node.childNodes && node.childNodes.length > 0) {
eachMutation(node.childNodes, fn)
}
}
}