Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save attila/46aca9c45623e8952274 to your computer and use it in GitHub Desktop.
Save attila/46aca9c45623e8952274 to your computer and use it in GitHub Desktop.
(function() {
'use strict';
var CSSCriticalPath = function(w, d, opts) {
var opt = opts || {
allowHosts: [
w.location.hostname
]
};
var css = {};
var pushCSS = function(r) {
if (!css[r.selectorText]) {
css[r.selectorText] = {};
}
var styles = r.style.cssText.split(/;(?![A-Za-z0-9])/);
for (var i = 0; i < styles.length; i++) {
if (!styles[i]) {
continue;
}
var pair = styles[i].split(': ');
pair[0] = pair[0].trim();
pair[1] = pair[1].trim();
css[r.selectorText][pair[0]] = pair[1];
}
};
var parseTree = function() {
// Get a list of all the elements in the view.
var height = w.innerHeight;
var walker = d.createTreeWalker(d, NodeFilter.SHOW_ELEMENT, function() {
return NodeFilter.FILTER_ACCEPT;
}, true);
while (walker.nextNode()) {
var node = walker.currentNode;
var rect = node.getBoundingClientRect();
if (rect.top < height || opt.scanFullPage) {
var rules = [];
rules.push.apply(rules, w.getMatchedCSSRules(node));
// Going forward, add pseudo-element rules too.
rules.push.apply(rules, w.getMatchedCSSRules(node, 'before'));
rules.push.apply(rules, w.getMatchedCSSRules(node, 'after'));
// Do not include if the style is not from an external stylesheet.
// This means that the rule is either inline already or inlined by JS.
if (!opt.keepInlineStyles) {
rules = rules.filter(function(e) {
return (!!e.parentStyleSheet.href);
});
}
if (!!rules) {
for (var r = 0; r < rules.length; r++) {
pushCSS(rules[r]);
}
}
}
}
};
this.generateCSS = function() {
var finalCSS = '';
for (var k in css) {
finalCSS += k + ' { ';
for (var j in css[k]) {
finalCSS += j + ': ' + css[k][j] + '; ';
}
finalCSS += '}\u000A';
}
return finalCSS;
};
parseTree();
};
var cp = new CSSCriticalPath(window, document);
var css = cp.generateCSS();
console.log(css);
}());
@attila
Copy link
Author

attila commented Feb 20, 2015

This version includes both before and after styles plus filters out styles that do not originate from an external stylesheet (e.g not from an already inline stylesheet and not from javascript setting them inline)

Also adjusted coding style to match our linter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment