Skip to content

Make images smaller using best-in-class codecs, right in the browser.

JavaScript

Add option to make async leave a rel="preload" in the header and append a <link rel="stylesheet"> to the end of body.

Jason Miller919a259b0a22
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 <link rel="stylesheet"> into <body> 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 <link rel="stylesheet"> to <link rel="preload" as="style" onload="this.rel='stylesheet'">
- async: true
+ // convert critical'd <link rel="stylesheet"> to <link rel="preload" as="style">:
+ async: true,
+ // copy original <link rel="stylesheet"> to the end of <body>:
+ preload: true
}),
// Inline constants during build, so they can be folded by UglifyJS.