From 919a259b0a22abcfe9c14d42cb50317e78632b9e Mon Sep 17 00:00:00 2001 From: Jason Miller Date: Thu, 5 Apr 2018 12:41:19 -0400 Subject: [PATCH] Add option to make async leave a rel="preload" in the header and append a to the end of body. --- config/critters-webpack-plugin.js | 12 ++++++++++-- webpack.config.js | 6 ++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/config/critters-webpack-plugin.js b/config/critters-webpack-plugin.js index 50598a64..f4aeaf55 100644 --- a/config/critters-webpack-plugin.js +++ b/config/critters-webpack-plugin.js @@ -20,7 +20,8 @@ const PARSE5_OPTS = { * @class * @param {Object} options * @param {Boolean} [options.external=true] Fetch and inline critical styles from external stylesheets - * @param {Boolean} [options.async=false] Convert critical-inlined external stylesheets to load asynchronously (via link rel="preload") + * @param {Boolean} [options.async=false] Convert critical-inlined external stylesheets to load asynchronously (via link rel="preload" - see https://filamentgroup.com/lab/async-css.html) + * @param {Boolean} [options.preload=false] (requires `async` option) Append a new into instead of swapping the preload's rel attribute * @param {Boolean} [options.compress=true] Compress resulting critical CSS */ module.exports = class CrittersWebpackPlugin { @@ -99,7 +100,14 @@ module.exports = class CrittersWebpackPlugin { if (this.options.async) { link.setAttribute('rel', 'preload'); link.setAttribute('as', 'style'); - link.setAttribute('onload', "this.rel='stylesheet'"); + if (this.options.preload) { + const bodyLink = document.createElement('link'); + bodyLink.setAttribute('rel', 'stylesheet'); + bodyLink.setAttribute('href', href); + document.body.appendChild(bodyLink); + } else { + link.setAttribute('onload', "this.rel='stylesheet'"); + } } }); } diff --git a/webpack.config.js b/webpack.config.js index d640dbf9..b2aacc79 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -177,8 +177,10 @@ module.exports = function(_, env) { isProd && new PreloadWebpackPlugin(), isProd && new CrittersPlugin({ - // convert critical'd to - async: true + // convert critical'd to : + async: true, + // copy original to the end of : + preload: true }), // Inline constants during build, so they can be folded by UglifyJS.