Skip to content

Instantly share code, notes, and snippets.

@kostasxyz
Created July 15, 2017 17:26
Show Gist options
  • Save kostasxyz/1541f2ab437d14c10797d6702d6a01c6 to your computer and use it in GitHub Desktop.
Save kostasxyz/1541f2ab437d14c10797d6702d6a01c6 to your computer and use it in GitHub Desktop.
Select all elements above the fold and append matched css rules in header
(function () {
document.addEventListener('DOMContentLoaded', function(){
var stylesheets = document.styleSheets;
var wHeight = window.innerHeight;
var criticalCSS = '';
var uniqueRules = [];
var criticalRules = [];
console.log(stylesheets);
function matchCssRules(node) {
var matchedRules = [];
node.matches = node.matches || node.webkitMatchesSelector || node.mozMatchesSelector || node.msMatchesSelector || node.oMatchesSelector;
for (var i = 0; i < stylesheets.length; i++) {
var rules = stylesheets[i].rules || stylesheets[i].cssRules;
if(rules) {
for (var r = 0; r < rules.length; r++) {
if(rules[r] instanceof CSSMediaRule || rules[r] instanceof CSSKeyframesRule) {
var mediaRules = rules[r].cssRules;
for (var m = 0; m < mediaRules.length; m++) {
if (node.matches(mediaRules[m].selectorText)) {
matchedRules.push(rules[r].cssText);
}
}
}
else {
if (node.matches(rules[r].selectorText)) {
matchedRules.push(rules[r].cssText);
}
}
}
}
}
return matchedRules;
}
var treeWalker = document.createTreeWalker(
document,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
false
);
while(treeWalker.nextNode()) {
var node = treeWalker.currentNode;
var rect = node.getBoundingClientRect();
if(rect.top < wHeight) {
var rules = matchCssRules(node);
if(rules) {
for(var i = 0; i < rules.length; i++) {
criticalRules.push(rules[i]);
}
}
}
}
uniqueRules = criticalRules.filter(function(e, i, s) {
return i == s.indexOf(e);
});
var head = document.getElementsByTagName('head')[0];
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
s.setAttribute('id', 'nvl_critical_css');
if (s.styleSheet) { // IE
s.styleSheet.cssText = uniqueRules;
}
else { // the world
s.appendChild(document.createTextNode(uniqueRules));
}
head.appendChild(s);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment