Last active
July 21, 2023 12:53
-
-
Save mike-at-redspace/18d7ae1168098dc93a366d4c06f37ec4 to your computer and use it in GitHub Desktop.
Grab above the fold css
This file contains 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
/** | |
* Get critical CSS and class names for elements matching a selector | |
*/ | |
function getCriticalCSS(selector) { | |
try { | |
const elements = document.querySelectorAll(selector); | |
const classNames = new Set(); | |
let css = ''; | |
elements.forEach(element => { | |
const classes = Array.from(element.classList) | |
.map(name => `.${name}`) | |
.join(' '); | |
classNames.add(classes); | |
const styles = getComputedStyle(element); | |
let cssDeclarations = ''; | |
for (let i = 0; i < styles.length; i++) { | |
const name = styles[i]; | |
const value = styles.getPropertyValue(name); | |
cssDeclarations += ` ${name}: ${value};\n`; | |
} | |
css += `${classes} {\n${cssDeclarations}}\n`; | |
}); | |
return css | |
} catch (error) { | |
// Handle errors | |
} | |
} | |
/** | |
* Simple CSS minifier | |
*/ | |
function minifyCSS(css) { | |
return css | |
.replace(/\n/g, '') | |
.replace(/\s{2,}/g, ' ') | |
.replace(/\s*([{}:;,>+\-\/])\s*/g, '$1'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment