Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
critical CSS devtool snippet
/**
* criticalCSS by @dansajin. based on @scottjehl's criticalcss.js
* run this in a browser console or create a bookmarklet.
* lists rules per css file.
* does not include cross origin css files and inline css.
*/
(function(){
var sheets = document.styleSheets,
host = window.location.host,
maxTop = 1200,
critical = [];
function aboveFoldCSS(rule){
if(!rule.selectorText){
return null;
}
var selectors = rule.selectorText.split(","),
criticalSelectors = [];
if(selectors.length){
for(var l in selectors){
var elem;
try {
// webkit is really strict about standard selectors getting passed-in
elem = document.querySelector(selectors[l]);
}
catch(e) {}
if(elem && elem.offsetTop <= maxTop){
criticalSelectors.push(selectors[l]);
}
}
}
if(criticalSelectors.length){
return criticalSelectors.join(",") + rule.cssText.match(/\{.+/);
}
return null;
}
critical.push('/* created by https://gist.github.com/dansajin/a65e7b7cdb8d9f05eac7eec55bf142af/ */');
for(var i in sheets)
{
var sheet = sheets[i],
href = sheet.href;
if(href && href.indexOf(host) > -1){
var rules = sheet.cssRules;
critical.push('/* file: ' + href + ' */');
for(var j in rules){
var media = rules[ j ].media,
matchingRules = [];
if(media){
var innerRules = rules[j].cssRules;
for(var k in innerRules){
var critCSSText = aboveFoldCSS(innerRules[k]);
if(critCSSText){
matchingRules.push(critCSSText);
}
}
if(matchingRules.length){
matchingRules.unshift("@media " + media.mediaText + "{");
matchingRules.push("}");
}
}
else{
var critCSSText = aboveFoldCSS(rules[j]);
if(critCSSText){
matchingRules.push(critCSSText);
}
}
if (matchingRules.length){
critical.push(matchingRules.join("\n"));
}
}
}
}
console.log(critical.join("\n"));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment