Merge pull request #3 from bevacqua/master

Extract inlined styles
This commit is contained in:
Ben Zörb 2014-10-23 00:15:37 +02:00
commit 2b8cdc4e91
10 changed files with 524 additions and 35 deletions

View File

@ -2,7 +2,7 @@ root = true
[*]
indent_style = space
indent_size = 4
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true

View File

@ -1,3 +1,8 @@
{
"laxcomma": true
"laxcomma": true,
"globals": {
"it": false,
"describe": false
},
"node": true
}

View File

@ -22,3 +22,16 @@ var critical = fs.readFileSync('test/fixtures/critical.css', 'utf8');
var inlined = inline(html, critical);
```
## `inline(html, styles, options?)
- `html` is the HTML you want to use to inline your critical styles, or any other styles
- `styles` are the styles you're looking to inline
- `options` is an optional configuration object
- `minify` will minify the styles before inlining
- `extract` will remove the inlined styles from any stylesheets referenced in the HTML
- `basePath` will be used when extracting styles to find the files references by `href` attributes
## License
MIT

View File

@ -9,17 +9,23 @@
* All rights reserved.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var cave = require('cave');
var reaver = require('reaver');
var cheerio = require('cheerio');
var CleanCSS = require('clean-css');
module.exports = function(html, styles, minify) {
module.exports = function(html, styles, options) {
var $ = cheerio.load(String(html));
var links = $('link[rel="stylesheet"]');
var noscript = $('<noscript>\n</noscript>');
var o = options || {};
// minify if minify option is set
if (minify) {
if (o.minify) {
styles = new CleanCSS().minify(styles);
}
@ -28,13 +34,33 @@ module.exports = function(html, styles, minify) {
// insert noscript block right after stylesheets
links.eq(0).first().after(noscript);
// wrap links to stylesheets in noscript block so that they will evaluated when js is turned off
var hrefs = links.map(function(idx, el) {
el = $(el);
return $(this).attr('href');
}).toArray();
// extract styles from stylesheets if extract option is set
if (o.extract) {
if (!o.basePath) {
throw new Error('Option `basePath` is missing and required when using `extract`!');
}
hrefs = hrefs.map(function(href) {
var file = path.resolve(o.basePath, href);
if (!fs.existsSync(file)) {
return;
}
var diff = cave(file, { css: styles });
fs.writeFileSync(reaver.rev(file, diff), diff);
return reaver.rev(href, diff);
});
}
// wrap links to stylesheets in noscript block so that they will evaluated when js is turned off
links.each(function (idx) {
var el = $(this);
el.attr('href', hrefs[idx]);
noscript.append(el);
noscript.append('\n');
return el.attr('href');
}).toArray();
});
// build js block to load blocking stylesheets
$('body').append('<script>\n' +

View File

@ -19,8 +19,10 @@
"url": "https://github.com/bezoerb/inline-critical/issues"
},
"dependencies": {
"cave": "^2.0.0",
"cheerio": "^0.17.0",
"clean-css": "^2.2.12"
"clean-css": "^2.2.12",
"reaver": "^1.2.0"
},
"devDependencies": {
"chai": "~1.8.1",

15
test/fixtures/cartoon-expected.css vendored Normal file
View File

@ -0,0 +1,15 @@
.cool {
color: #f00;
}
#not {
color: #f00;
}
body {
color: #f00;
}
.foo {
color: #f00;
}

15
test/fixtures/cartoon.18d89c7f.css vendored Normal file
View File

@ -0,0 +1,15 @@
.cool {
color: #f00;
}
#not {
color: #f00;
}
body {
color: #f00;
}
.foo {
color: #f00;
}

306
test/fixtures/cartoon.css vendored Normal file
View File

@ -0,0 +1,306 @@
.cool {
color: #f00;
}
#not {
color: #f00;
}
body {
color: #f00;
}
body {
padding-top: 20px;
padding-bottom: 20px;
}
.header{
padding-left: 15px;
padding-right: 15px;
}
.header {
border-bottom: 1px solid #e5e5e5;
}
.header h3 {
margin-top: 0;
margin-bottom: 0;
line-height: 40px;
padding-bottom: 19px;
}
.jumbotron {
text-align: center;
border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
font-size: 21px;
padding: 14px 24px;
}
@media screen and (min-width: 768px) {
.container {
max-width: 730px;
}
.header{
padding-left: 0;
padding-right: 0;
}
.header {
margin-bottom: 30px;
}
.jumbotron {
border-bottom: 0;
}
}
html {
font-family: sans-serif;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
body {
margin: 0;
}
a {
background: transparent;
}
h1 {
margin: .67em 0;
font-size: 2em;
}
@media print {
* {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
box-shadow: none !important;
}
a{
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
a[href^="#"]:after {
content: "";
}
p,
h3 {
orphans: 3;
widows: 3;
}
h3 {
page-break-after: avoid;
}
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 62.5%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
background-color: #fff;
}
a {
color: #428bca;
text-decoration: none;
}
h1,
h3{
font-family: inherit;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1,
h3{
margin-top: 20px;
margin-bottom: 10px;
}
h1{
font-size: 36px;
}
h3{
font-size: 24px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 200;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
.text-muted {
color: #999;
}
ul{
margin-top: 0;
margin-bottom: 10px;
}
.container {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.btn {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.42857143;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.btn-success {
color: #fff;
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-lg{
padding: 10px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
.nav {
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a{
color: #fff;
background-color: #428bca;
}
.jumbotron {
padding: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eee;
}
.jumbotron h1{
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.container .jumbotron {
border-radius: 6px;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron {
padding-right: 60px;
padding-left: 60px;
}
.jumbotron h1{
font-size: 63px;
}
}
.container:before,
.container:after,
.nav:before,
.nav:after{
display: table;
content: " ";
}
.container:after,
.nav:after{
clear: both;
}
.pull-right {
float: right !important;
}
.foo {
color: #f00;
}

88
test/fixtures/cartoon.html vendored Normal file
View File

@ -0,0 +1,88 @@
<!doctype html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title>critical css test</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css styles/main.css -->
<link rel="stylesheet" href="cartoon.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbuild -->
</head>
<body>
<!--[if lt IE 10]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<div class="container">
<div class="header">
<ul class="nav nav-pills pull-right">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
<h3 class="text-muted">critical css test</h3>
</div>
<div class="jumbotron">
<h1>'Allo, 'Allo!</h1>
<p class="lead">Always a pleasure scaffolding your apps.</p>
<p><a class="btn btn-lg btn-success" href="#">Splendid!</a></p>
</div>
<div class="row marketing">
<div class="col-lg-6">
<h4>HTML5 Boilerplate</h4>
<p>HTML5 Boilerplate is a professional front-end template for building fast, robust, and adaptable web apps or sites.</p>
<h4>Bootstrap</h4>
<p>Sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development.</p>
</div>
</div>
<div class="footer">
<p>♥ from the Yeoman team</p>
</div>
</div>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X');ga('send','pageview');
</script>
<!-- build:js scripts/vendor.js -->
<!-- bower:js -->
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<!-- endbower -->
<!-- endbuild -->
<!-- build:js scripts/plugins.js -->
<script src="bower_components/bootstrap/js/affix.js"></script>
<script src="bower_components/bootstrap/js/alert.js"></script>
<script src="bower_components/bootstrap/js/dropdown.js"></script>
<script src="bower_components/bootstrap/js/tooltip.js"></script>
<script src="bower_components/bootstrap/js/modal.js"></script>
<script src="bower_components/bootstrap/js/transition.js"></script>
<script src="bower_components/bootstrap/js/button.js"></script>
<script src="bower_components/bootstrap/js/popover.js"></script>
<script src="bower_components/bootstrap/js/carousel.js"></script>
<script src="bower_components/bootstrap/js/scrollspy.js"></script>
<script src="bower_components/bootstrap/js/collapse.js"></script>
<script src="bower_components/bootstrap/js/tab.js"></script>
<!-- endbuild -->
<!-- build:js scripts/main.js -->
<script src="scripts/main.js"></script>
<!-- endbuild -->
</body>
</html>

View File

@ -1,39 +1,58 @@
var expect = require('chai').expect,
fs = require('fs'),
inlineCritical = require('..');
'use strict';
/**
* Strip whitespaces, tabs and newlines and replace with one space.
* Usefull when comparing string contents.
* @param string
*/
function stripWhitespace(string) {
return string.replace(/[\r\n]+/mg,' ').replace(/\s+/gm,'');
var expect = require('chai').expect;
var reaver = require('reaver');
var fs = require('fs');
var inlineCritical = require('..');
function strip(string) {
return string.replace(/[\r\n]+/mg,' ').replace(/\s+/gm,'');
}
function read (file) {
return fs.readFileSync(file, 'utf8');
}
function write (file, data) {
fs.writeFileSync(file, data);
}
describe('inline-critical', function() {
it('should inline css', function(done) {
var html = fs.readFileSync('test/fixtures/index.html', 'utf8');
var css = fs.readFileSync('test/fixtures/critical.css', 'utf8');
it('should inline css', function(done) {
var html = read('test/fixtures/index.html');
var css = read('test/fixtures/critical.css');
var expected = fs.readFileSync('test/fixtures/index-inlined-async-final.html', 'utf8');
var out = inlineCritical(html, css);
var expected = read('test/fixtures/index-inlined-async-final.html');
var out = inlineCritical(html, css);
expect(stripWhitespace(out.toString('utf-8'))).to.be.equal(stripWhitespace(expected));
expect(strip(out.toString('utf-8'))).to.be.equal(strip(expected));
done();
});
done();
});
it('should inline and minify css', function(done) {
var html = fs.readFileSync('test/fixtures/index.html', 'utf8');
var css = fs.readFileSync('test/fixtures/critical.css', 'utf8');
it('should inline and minify css', function(done) {
var html = read('test/fixtures/index.html');
var css = read('test/fixtures/critical.css');
var expected = fs.readFileSync('test/fixtures/index-inlined-async-minified-final.html', 'utf8');
var out = inlineCritical(html, css, true);
var expected = read('test/fixtures/index-inlined-async-minified-final.html');
var out = inlineCritical(html, css, { minify: true });
expect(stripWhitespace(out.toString('utf-8'))).to.be.equal(stripWhitespace(expected));
expect(strip(out.toString('utf-8'))).to.be.equal(strip(expected));
done();
});
done();
});
it('should inline and extract css', function(done) {
var html = read('test/fixtures/cartoon.html');
var css = read('test/fixtures/critical.css');
var expected = read('test/fixtures/cartoon-expected.css');
inlineCritical(html, css, { extract: true, basePath: 'test/fixtures' });
expect(read(reaver.rev('test/fixtures/cartoon.css', expected))).to.be.equal(expected);
done();
});
});