-
-
Save gnanet/6e4d48c1e1221cdc17dae47d7a3b3390 to your computer and use it in GitHub Desktop.
Select all elements above the fold and append matched css rules in header
This file contains hidden or 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
(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