zss-engine
Version:
Zero-runtime StyleSheet Engine
52 lines (51 loc) • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createStyleElement = createStyleElement;
exports.injectClientCSS = injectClientCSS;
const index_js_1 = require("../index.js");
const styleSheets = {};
const hashCache = {};
function createStyleElement(hash) {
if (document.getElementById(hash))
return null;
const styleElement = document.createElement('style');
styleElement.setAttribute('id', hash);
styleElement.setAttribute('type', 'text/css');
styleSheets[hash] = styleElement;
document.head.appendChild(styleElement);
return styleSheets[hash];
}
function injectClientCSS(hash, sheet) {
if (index_js_1.isServer)
return;
requestAnimationFrame(() => {
styleCleanUp();
});
hashCache[hash] = hash;
const styleElement = createStyleElement(hash);
if (styleElement == null)
return;
styleElement.textContent = sheet;
}
function styleCleanUp() {
requestAnimationFrame(() => {
for (const hash in hashCache) {
const classElements = document.querySelectorAll(`[class*="${hash}"]`);
if (classElements.length === 0) {
removeStyleElement(hashCache[hash]);
}
}
});
}
function removeStyleElement(hash) {
if (styleSheets[hash]) {
delete styleSheets[hash];
if (hashCache.hasOwnProperty.call(hashCache, hash)) {
delete hashCache[hash];
}
const styleElement = document.getElementById(hash);
if (styleElement) {
document.head.removeChild(styleElement);
}
}
}