-
Notifications
You must be signed in to change notification settings - Fork 0
/
use.js
47 lines (42 loc) · 1.04 KB
/
use.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const apply = (func, node) => {
if (typeof func == "function") {
func(node)
} else if ("then" in func) {
func.then(result => apply(result, node))
} else if ("default" in func) {
apply(func.default, node)
}
}
export const use = node => {
const code = Function("return (" + node.getAttribute("use") + ")")
node.removeAttribute("use")
const func = code()
apply(func, node)
}
export const observe = (root = document) => {
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.hasAttribute("use")) {
use(node)
}
})
})
})
observer.observe(root, {subtree: true, childList: true})
return observer
}
export const run = (root = document) => {
root.querySelectorAll("[use]").forEach(use)
}
export const whenReady = () => {
if (document.readyState == "complete")
run(document)
else
document.addEventListener("readystatechange", whenReady, {once: true})
}
export const install = () => {
observe(document)
run(document)
}
export default install