inline-critical/index.js

173 lines
5.3 KiB
JavaScript
Raw Normal View History

2014-08-04 00:01:39 +02:00
/**
* Module to inline styles while loading the existing stylesheets async
*
* @author Ben Zörb @bezoerb https://github.com/bezoerb
* @copyright Copyright (c) 2014 Ben Zörb
*
* Licensed under the MIT license.
* http://bezoerb.mit-license.org/
* All rights reserved.
*/
'use strict';
2017-03-20 22:42:19 +01:00
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const UglifyJS = require('uglify-js');
const cave = require('cave');
const reaver = require('reaver');
const cheerio = require('cheerio');
const render = require('dom-serializer');
const parse = require('cheerio/lib/parse');
const CleanCSS = require('clean-css');
const slash = require('slash');
const normalizeNewline = require('normalize-newline');
const resolve = require('resolve');
const detectIndent = require('detect-indent');
/**
* Get loadcss + cssrelpreload script
*
* @returns {string}
*/
function getScript() {
2017-03-20 22:42:19 +01:00
const loadCssMain = resolve.sync('fg-loadcss');
const loadCssBase = path.dirname(loadCssMain);
const loadCSS = read(path.join(loadCssBase, 'cssrelpreload.js'));
2017-05-19 23:33:21 +02:00
return UglifyJS.minify(loadCSS).code;
}
2014-12-08 23:02:01 +01:00
2014-11-25 17:21:43 +01:00
/**
* Fixup slashes in file paths for windows
*
2014-12-08 23:15:13 +01:00
* @param {string} str
* @return {string}
2014-11-25 17:21:43 +01:00
*/
function normalizePath(str) {
2015-11-13 22:59:10 +01:00
return process.platform === 'win32' ? slash(str) : str;
2014-11-25 17:21:43 +01:00
}
2014-08-04 00:01:39 +02:00
2014-12-08 23:15:13 +01:00
/**
* Read file *
* @param {string} file
* @returns {string}
*/
2015-06-10 18:07:48 +02:00
function read(file) {
2015-11-13 22:59:10 +01:00
return fs.readFileSync(file, 'utf8');
2014-12-08 23:02:01 +01:00
}
2016-04-17 00:50:40 +02:00
/**
* Get the indentation of the link tags
* @param html
* @param $el
*/
function getIndent(html, $el) {
2017-03-20 22:42:19 +01:00
const regName = new RegExp(_.escapeRegExp(_.get($el, 'name')));
const regHref = new RegExp(_.escapeRegExp(_.get($el, 'attribs.href')));
const regRel = new RegExp(_.escapeRegExp(_.get($el, 'attribs.rel')));
const lines = _.filter(html.split(/[\r\n]+/), line => {
2016-04-17 00:50:40 +02:00
return regName.test(line) && regHref.test(line) && regRel.test(line);
});
return detectIndent(lines.join('\n')).indent;
}
2015-06-10 18:07:48 +02:00
module.exports = function (html, styles, options) {
2016-04-18 06:35:08 +02:00
if (!_.isString(html)) {
html = String(html);
}
2017-03-20 22:42:19 +01:00
const $ = cheerio.load(html, {
2015-11-13 22:59:10 +01:00
decodeEntities: false
2015-06-09 07:12:09 +02:00
});
2017-03-20 22:42:19 +01:00
const allLinks = $('link[rel="stylesheet"], link[rel="preload"][as="style"]').filter(function () {
2015-11-13 22:59:10 +01:00
return !$(this).parents('noscript').length;
});
2015-06-09 07:12:09 +02:00
2017-03-20 22:42:19 +01:00
let links = allLinks.filter('[rel="stylesheet"]');
2016-04-17 00:50:40 +02:00
2017-03-20 22:42:19 +01:00
const o = _.assign({
2016-04-17 00:58:04 +02:00
minify: true
2016-04-17 00:50:40 +02:00
}, options || {});
const target = o.selector || allLinks.get(0) || $('head script').get(0);
2018-03-05 21:19:29 +01:00
const {indent} = detectIndent(html);
2017-03-20 22:42:19 +01:00
const targetIndent = getIndent(html, target);
const $target = $(target);
2015-11-13 22:59:10 +01:00
if (_.isString(o.ignore)) {
o.ignore = [o.ignore];
}
2015-11-13 22:59:10 +01:00
if (o.ignore) {
2017-03-20 22:42:19 +01:00
links = _.filter(links, link => {
const href = $(link).attr('href');
return _.findIndex(options.ignore, arg => {
2016-09-02 23:52:54 +02:00
return (_.isRegExp(arg) && arg.test(href)) || arg === href;
}) === -1;
});
}
2017-03-20 22:42:19 +01:00
// Minify if minify option is set
2015-11-13 22:59:10 +01:00
if (o.minify) {
2018-03-05 21:19:29 +01:00
styles = new CleanCSS().minify(styles).styles; // eslint-disable-line prefer-destructuring
2015-11-13 22:59:10 +01:00
}
2014-10-20 16:44:53 +02:00
if (styles) {
const elements = [
'<style>',
indent + styles.replace(/(\r\n|\r|\n)/g, '$1' + targetIndent + indent).replace(/^[\s\t]+$/g, ''),
'</style>', ''
].join('\n' + targetIndent).replace(/(\r\n|\r|\n)[\s\t]+(\r\n|\r|\n)/g, '$1$2');
if ($target.length > 0) {
// Insert inline styles right before first <link rel="stylesheet" /> or other target
$target.before(elements);
} else {
// Just append to the head
$('head').append(elements);
}
}
2015-11-13 22:59:10 +01:00
2016-10-17 06:38:15 +02:00
if (links.length > 0) {
2017-03-20 22:42:19 +01:00
// Modify links and ad clones to noscript block
2016-04-17 00:50:40 +02:00
$(links).each(function (idx, el) {
if (o.extract && !o.basePath) {
2015-11-13 22:59:10 +01:00
throw new Error('Option `basePath` is missing and required when using `extract`!');
}
2016-04-17 00:50:40 +02:00
2017-03-20 22:42:19 +01:00
const $el = $(el);
const elIndent = getIndent(html, el);
2016-04-17 00:50:40 +02:00
if (o.extract) {
2017-03-20 22:42:19 +01:00
const href = $el.attr('href');
const file = path.resolve(path.join(o.basePath, href));
2016-04-17 00:50:40 +02:00
if (fs.existsSync(file)) {
2017-03-20 22:42:19 +01:00
const diff = normalizeNewline(cave(file, {css: styles}));
2016-04-17 00:50:40 +02:00
fs.writeFileSync(reaver.rev(file, diff), diff);
$el.attr('href', normalizePath(reaver.rev(href, diff)));
2015-11-13 22:59:10 +01:00
}
2016-04-17 00:50:40 +02:00
}
2017-03-20 22:42:19 +01:00
// Add each fallback right behind the current style to keep source order when ignoring stylesheets
2016-04-18 16:49:29 +02:00
$el.after('\n' + elIndent + '<noscript>' + render(this) + '</noscript>');
2016-04-17 00:50:40 +02:00
2017-03-20 22:42:19 +01:00
// Add preload atttibutes to actual link element
2016-04-17 00:50:40 +02:00
$el.attr('rel', 'preload');
$el.attr('as', 'style');
$el.attr('onload', 'this.onload=null;this.rel=\'stylesheet\'');
2015-11-13 22:59:10 +01:00
});
2017-03-20 22:42:19 +01:00
// Add loadcss + cssrelpreload polyfill
const scriptAnchor = $('link[rel="stylesheet"], noscript').filter(function () {
2016-04-17 00:50:40 +02:00
return !$(this).parents('noscript').length;
}).last().get(0);
$(scriptAnchor).after('\n' + targetIndent + '<script>' + getScript() + '</script>');
2015-11-13 22:59:10 +01:00
}
2015-02-17 00:59:53 +01:00
2017-03-20 22:42:19 +01:00
const dom = parse($.html());
const markup = render(dom);
2015-02-17 00:59:53 +01:00
2017-03-20 22:42:19 +01:00
return Buffer.from(markup);
2014-08-04 00:01:39 +02:00
};