-
Notifications
You must be signed in to change notification settings - Fork 0
/
x-style-nano.js
52 lines (50 loc) · 1.2 KB
/
x-style-nano.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
48
49
50
51
52
/**
* x-style
* @param {string} attr - HTML attribute that contains the css, usually "x-style"
*/
((attr) => {
var styleEl,
style = "",
processedCss = {},
doc = document,
rawCss,
selectorAttr,
nextId = 1,
id;
var processEl = (el) => {
rawCss = el.getAttribute?.(attr);
if (rawCss) {
id = processedCss[rawCss] ??= nextId;
selectorAttr = attr + id;
el.removeAttribute(el[attr]);
el.setAttribute(selectorAttr, "");
el[attr] = selectorAttr;
if (id == nextId) {
style += `[${selectorAttr}]{${rawCss}}`;
nextId++;
}
}
};
new MutationObserver((mutations) => {
mutations.map((mutation) => {
if (mutation.type == "childList") {
mutation.addedNodes.forEach((el) => {
processEl(el);
[...(el.querySelectorAll?.(`[${attr}]`) || [])].map(processEl);
});
} else {
processEl(mutation.target);
}
});
if (style) {
styleEl = doc.createElement("style");
styleEl.innerHTML = style;
doc.head.appendChild(styleEl);
style = "";
}
}).observe(doc, {
attributeFilter: [attr],
childList: true,
subtree: true,
});
})("x-style");