Skip to content

Instantly share code, notes, and snippets.

@mike-at-redspace
Last active July 21, 2023 12:53
Show Gist options
  • Save mike-at-redspace/18d7ae1168098dc93a366d4c06f37ec4 to your computer and use it in GitHub Desktop.
Save mike-at-redspace/18d7ae1168098dc93a366d4c06f37ec4 to your computer and use it in GitHub Desktop.
Grab above the fold css
/**
* 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