[6a3a178] | 1 | /**
|
---|
| 2 | * Copyright 2018 Google LLC
|
---|
| 3 | *
|
---|
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
---|
| 5 | * use this file except in compliance with the License. You may obtain a copy of
|
---|
| 6 | * the License at
|
---|
| 7 | *
|
---|
| 8 | * http://www.apache.org/licenses/LICENSE-2.0
|
---|
| 9 | *
|
---|
| 10 | * Unless required by applicable law or agreed to in writing, software
|
---|
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
---|
| 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
---|
| 13 | * License for the specific language governing permissions and limitations under
|
---|
| 14 | * the License.
|
---|
| 15 | */
|
---|
| 16 |
|
---|
| 17 | import path from 'path';
|
---|
| 18 | import prettyBytes from 'pretty-bytes';
|
---|
| 19 | import sources from 'webpack-sources';
|
---|
| 20 | import postcss from 'postcss';
|
---|
| 21 | import cssnano from 'cssnano';
|
---|
| 22 | import log from 'webpack-log';
|
---|
| 23 | import minimatch from 'minimatch';
|
---|
| 24 | import { createDocument, serializeDocument, setNodeText } from './dom';
|
---|
| 25 | import {
|
---|
| 26 | parseStylesheet,
|
---|
| 27 | serializeStylesheet,
|
---|
| 28 | walkStyleRules,
|
---|
| 29 | walkStyleRulesWithReverseMirror,
|
---|
| 30 | markOnly,
|
---|
| 31 | applyMarkedSelectors,
|
---|
| 32 | } from './css';
|
---|
| 33 | import { tap } from './util';
|
---|
| 34 |
|
---|
| 35 | // Used to annotate this plugin's hooks in Tappable invocations
|
---|
| 36 | const PLUGIN_NAME = 'critters-webpack-plugin';
|
---|
| 37 |
|
---|
| 38 | /**
|
---|
| 39 | * The mechanism to use for lazy-loading stylesheets.
|
---|
| 40 | * _[JS]_ indicates that a strategy requires JavaScript (falls back to `<noscript>`).
|
---|
| 41 | *
|
---|
| 42 | * - **default:** Move stylesheet links to the end of the document and insert preload meta tags in their place.
|
---|
| 43 | * - **"body":** Move all external stylesheet links to the end of the document.
|
---|
| 44 | * - **"media":** Load stylesheets asynchronously by adding `media="not x"` and removing once loaded. _[JS]_
|
---|
| 45 | * - **"swap":** Convert stylesheet links to preloads that swap to `rel="stylesheet"` once loaded. _[JS]_
|
---|
| 46 | * - **"js":** Inject an asynchronous CSS loader similar to [LoadCSS](https://github.com/filamentgroup/loadCSS) and use it to load stylesheets. _[JS]_
|
---|
| 47 | * - **"js-lazy":** Like `"js"`, but the stylesheet is disabled until fully loaded.
|
---|
| 48 | * @typedef {(default|'body'|'media'|'swap'|'js'|'js-lazy')} PreloadStrategy
|
---|
| 49 | * @public
|
---|
| 50 | */
|
---|
| 51 |
|
---|
| 52 | /**
|
---|
| 53 | * Controls which keyframes rules are inlined.
|
---|
| 54 | *
|
---|
| 55 | * - **"critical":** _(default)_ inline keyframes rules that are used by the critical CSS.
|
---|
| 56 | * - **"all":** Inline all keyframes rules.
|
---|
| 57 | * - **"none":** Remove all keyframes rules.
|
---|
| 58 | * @typedef {('critical'|'all'|'none')} KeyframeStrategy
|
---|
| 59 | * @private
|
---|
| 60 | * @property {String} keyframes Which {@link KeyframeStrategy keyframe strategy} to use (default: `critical`)_
|
---|
| 61 | */
|
---|
| 62 |
|
---|
| 63 | /**
|
---|
| 64 | * Controls log level of the plugin. Specifies the level the logger should use. A logger will
|
---|
| 65 | * not produce output for any log level beneath the specified level. Available levels and order
|
---|
| 66 | * are:
|
---|
| 67 | *
|
---|
| 68 | * - **"info"** _(default)_
|
---|
| 69 | * - **"warn"**
|
---|
| 70 | * - **"error"**
|
---|
| 71 | * - **"trace"**
|
---|
| 72 | * - **"debug"**
|
---|
| 73 | * - **"silent"**
|
---|
| 74 | * @typedef {('info'|'warn'|'error'|'trace'|'debug'|'silent')} LogLevel
|
---|
| 75 | * @public
|
---|
| 76 | */
|
---|
| 77 |
|
---|
| 78 | /**
|
---|
| 79 | * All optional. Pass them to `new Critters({ ... })`.
|
---|
| 80 | * @public
|
---|
| 81 | * @typedef Options
|
---|
| 82 | * @property {Boolean} external Inline styles from external stylesheets _(default: `true`)_
|
---|
| 83 | * @property {Number} inlineThreshold Inline external stylesheets smaller than a given size _(default: `0`)_
|
---|
| 84 | * @property {Number} minimumExternalSize If the non-critical external stylesheet would be below this size, just inline it _(default: `0`)_
|
---|
| 85 | * @property {Boolean} pruneSource Remove inlined rules from the external stylesheet _(default: `true`)_
|
---|
| 86 | * @property {Boolean} mergeStylesheets Merged inlined stylesheets into a single <style> tag _(default: `true`)_
|
---|
| 87 | * @property {String[]} additionalStylesheets Glob for matching other stylesheets to be used while looking for critical CSS _(default: ``)_.
|
---|
| 88 | * @property {String} preload Which {@link PreloadStrategy preload strategy} to use
|
---|
| 89 | * @property {Boolean} noscriptFallback Add `<noscript>` fallback to JS-based strategies
|
---|
| 90 | * @property {Boolean} inlineFonts Inline critical font-face rules _(default: `false`)_
|
---|
| 91 | * @property {Boolean} preloadFonts Preloads critical fonts _(default: `true`)_
|
---|
| 92 | * @property {Boolean} fonts Shorthand for setting `inlineFonts`+`preloadFonts`
|
---|
| 93 | * - Values:
|
---|
| 94 | * - `true` to inline critical font-face rules and preload the fonts
|
---|
| 95 | * - `false` to don't inline any font-face rules and don't preload fonts
|
---|
| 96 | * @property {String} keyframes Controls which keyframes rules are inlined.
|
---|
| 97 | * - Values:
|
---|
| 98 | * - `"critical"`: _(default)_ inline keyframes rules used by the critical CSS
|
---|
| 99 | * - `"all"` inline all keyframes rules
|
---|
| 100 | * - `"none"` remove all keyframes rules
|
---|
| 101 | * @property {Boolean} compress Compress resulting critical CSS _(default: `true`)_
|
---|
| 102 | * @property {String} logLevel Controls {@link LogLevel log level} of the plugin _(default: `"info"`)_
|
---|
| 103 | */
|
---|
| 104 |
|
---|
| 105 | /**
|
---|
| 106 | * Create a Critters plugin instance with the given options.
|
---|
| 107 | * @public
|
---|
| 108 | * @param {Options} options Options to control how Critters inlines CSS.
|
---|
| 109 | * @example
|
---|
| 110 | * // webpack.config.js
|
---|
| 111 | * module.exports = {
|
---|
| 112 | * plugins: [
|
---|
| 113 | * new Critters({
|
---|
| 114 | * // Outputs: <link rel="preload" onload="this.rel='stylesheet'">
|
---|
| 115 | * preload: 'swap',
|
---|
| 116 | *
|
---|
| 117 | * // Don't inline critical font-face rules, but preload the font URLs:
|
---|
| 118 | * preloadFonts: true
|
---|
| 119 | * })
|
---|
| 120 | * ]
|
---|
| 121 | * }
|
---|
| 122 | */
|
---|
| 123 | export default class Critters {
|
---|
| 124 | /** @private */
|
---|
| 125 | constructor(options) {
|
---|
| 126 | this.options = Object.assign(
|
---|
| 127 | { logLevel: 'info', externalStylesheets: [] },
|
---|
| 128 | options || {}
|
---|
| 129 | );
|
---|
| 130 | this.options.pruneSource = this.options.pruneSource !== false;
|
---|
| 131 | this.urlFilter = this.options.filter;
|
---|
| 132 | if (this.urlFilter instanceof RegExp) {
|
---|
| 133 | this.urlFilter = this.urlFilter.test.bind(this.urlFilter);
|
---|
| 134 | }
|
---|
| 135 | this.logger = log({
|
---|
| 136 | name: 'Critters',
|
---|
| 137 | unique: true,
|
---|
| 138 | level: this.options.logLevel,
|
---|
| 139 | });
|
---|
| 140 | }
|
---|
| 141 |
|
---|
| 142 | /**
|
---|
| 143 | * Invoked by Webpack during plugin initialization
|
---|
| 144 | */
|
---|
| 145 | apply(compiler) {
|
---|
| 146 | // hook into the compiler to get a Compilation instance...
|
---|
| 147 | tap(compiler, 'compilation', PLUGIN_NAME, false, (compilation) => {
|
---|
| 148 | // ... which is how we get an "after" hook into html-webpack-plugin's HTML generation.
|
---|
| 149 | if (
|
---|
| 150 | compilation.hooks &&
|
---|
| 151 | compilation.hooks.htmlWebpackPluginAfterHtmlProcessing
|
---|
| 152 | ) {
|
---|
| 153 | tap(
|
---|
| 154 | compilation,
|
---|
| 155 | 'html-webpack-plugin-after-html-processing',
|
---|
| 156 | PLUGIN_NAME,
|
---|
| 157 | true,
|
---|
| 158 | (htmlPluginData, callback) => {
|
---|
| 159 | this.process(compiler, compilation, htmlPluginData.html)
|
---|
| 160 | .then((html) => {
|
---|
| 161 | callback(null, { html });
|
---|
| 162 | })
|
---|
| 163 | .catch(callback);
|
---|
| 164 | }
|
---|
| 165 | );
|
---|
| 166 | } else {
|
---|
| 167 | // If html-webpack-plugin isn't used, process the first HTML asset as an optimize step
|
---|
| 168 | tap(
|
---|
| 169 | compilation,
|
---|
| 170 | 'optimize-assets',
|
---|
| 171 | PLUGIN_NAME,
|
---|
| 172 | true,
|
---|
| 173 | (assets, callback) => {
|
---|
| 174 | let htmlAssetName;
|
---|
| 175 | for (const name in assets) {
|
---|
| 176 | if (name.match(/\.html$/)) {
|
---|
| 177 | htmlAssetName = name;
|
---|
| 178 | break;
|
---|
| 179 | }
|
---|
| 180 | }
|
---|
| 181 | if (!htmlAssetName) {
|
---|
| 182 | return callback(Error('Could not find HTML asset.'));
|
---|
| 183 | }
|
---|
| 184 | const html = assets[htmlAssetName].source();
|
---|
| 185 | if (!html) return callback(Error('Empty HTML asset.'));
|
---|
| 186 |
|
---|
| 187 | this.process(compiler, compilation, String(html))
|
---|
| 188 | .then((html) => {
|
---|
| 189 | assets[htmlAssetName] = new sources.RawSource(html);
|
---|
| 190 | callback();
|
---|
| 191 | })
|
---|
| 192 | .catch(callback);
|
---|
| 193 | }
|
---|
| 194 | );
|
---|
| 195 | }
|
---|
| 196 | });
|
---|
| 197 | }
|
---|
| 198 |
|
---|
| 199 | /**
|
---|
| 200 | * Read the contents of a file from Webpack's input filesystem
|
---|
| 201 | */
|
---|
| 202 | readFile(compilation, filename) {
|
---|
| 203 | const fs = this.fs || compilation.outputFileSystem;
|
---|
| 204 | return new Promise((resolve, reject) => {
|
---|
| 205 | const callback = (err, data) => {
|
---|
| 206 | if (err) reject(err);
|
---|
| 207 | else resolve(data);
|
---|
| 208 | };
|
---|
| 209 | if (fs && fs.readFile) {
|
---|
| 210 | fs.readFile(filename, callback);
|
---|
| 211 | } else {
|
---|
| 212 | require('fs').readFile(filename, 'utf8', callback);
|
---|
| 213 | }
|
---|
| 214 | });
|
---|
| 215 | }
|
---|
| 216 |
|
---|
| 217 | /**
|
---|
| 218 | * Apply critical CSS processing to html-webpack-plugin
|
---|
| 219 | */
|
---|
| 220 | async process(compiler, compilation, html) {
|
---|
| 221 | const outputPath = compiler.options.output.path;
|
---|
| 222 | const publicPath = compiler.options.output.publicPath;
|
---|
| 223 |
|
---|
| 224 | // Parse the generated HTML in a DOM we can mutate
|
---|
| 225 | const document = createDocument(html);
|
---|
| 226 |
|
---|
| 227 | if (this.options.additionalStylesheets) {
|
---|
| 228 | const styleSheetsIncluded = [];
|
---|
| 229 | (this.options.additionalStylesheets || []).forEach((cssFile) => {
|
---|
| 230 | if (styleSheetsIncluded.includes(cssFile)) {
|
---|
| 231 | return;
|
---|
| 232 | }
|
---|
| 233 | styleSheetsIncluded.push(cssFile);
|
---|
| 234 | const webpackCssAssets = Object.keys(
|
---|
| 235 | compilation.assets
|
---|
| 236 | ).filter((file) => minimatch(file, cssFile));
|
---|
| 237 | webpackCssAssets.map((asset) => {
|
---|
| 238 | const tag = document.createElement('style');
|
---|
| 239 | tag.innerHTML = compilation.assets[asset].source();
|
---|
| 240 | document.head.appendChild(tag);
|
---|
| 241 | });
|
---|
| 242 | });
|
---|
| 243 | }
|
---|
| 244 |
|
---|
| 245 | // `external:false` skips processing of external sheets
|
---|
| 246 | if (this.options.external !== false) {
|
---|
| 247 | const externalSheets = [].slice.call(
|
---|
| 248 | document.querySelectorAll('link[rel="stylesheet"]')
|
---|
| 249 | );
|
---|
| 250 | await Promise.all(
|
---|
| 251 | externalSheets.map((link) =>
|
---|
| 252 | this.embedLinkedStylesheet(link, compilation, outputPath, publicPath)
|
---|
| 253 | )
|
---|
| 254 | );
|
---|
| 255 | }
|
---|
| 256 |
|
---|
| 257 | // go through all the style tags in the document and reduce them to only critical CSS
|
---|
| 258 | const styles = [].slice.call(document.querySelectorAll('style'));
|
---|
| 259 | await Promise.all(
|
---|
| 260 | styles.map((style) => this.processStyle(style, document))
|
---|
| 261 | );
|
---|
| 262 |
|
---|
| 263 | if (this.options.mergeStylesheets !== false && styles.length !== 0) {
|
---|
| 264 | await this.mergeStylesheets(document);
|
---|
| 265 | }
|
---|
| 266 |
|
---|
| 267 | // serialize the document back to HTML and we're done
|
---|
| 268 | return serializeDocument(document);
|
---|
| 269 | }
|
---|
| 270 |
|
---|
| 271 | async mergeStylesheets(document) {
|
---|
| 272 | const styles = [].slice.call(document.querySelectorAll('style'));
|
---|
| 273 | if (styles.length === 0) {
|
---|
| 274 | this.logger.warn(
|
---|
| 275 | 'Merging inline stylesheets into a single <style> tag skipped, no inline stylesheets to merge'
|
---|
| 276 | );
|
---|
| 277 | return;
|
---|
| 278 | }
|
---|
| 279 | const first = styles[0];
|
---|
| 280 | let sheet = first.textContent;
|
---|
| 281 | for (let i = 1; i < styles.length; i++) {
|
---|
| 282 | const node = styles[i];
|
---|
| 283 | sheet += node.textContent;
|
---|
| 284 | node.remove();
|
---|
| 285 | }
|
---|
| 286 | if (this.options.compress !== false) {
|
---|
| 287 | const before = sheet;
|
---|
| 288 | const processor = postcss([cssnano()]);
|
---|
| 289 | const result = await processor.process(before, { from: undefined });
|
---|
| 290 | // @todo sourcemap support (elsewhere first)
|
---|
| 291 | sheet = result.css;
|
---|
| 292 | }
|
---|
| 293 | setNodeText(first, sheet);
|
---|
| 294 | }
|
---|
| 295 |
|
---|
| 296 | /**
|
---|
| 297 | * Inline the target stylesheet referred to by a <link rel="stylesheet"> (assuming it passes `options.filter`)
|
---|
| 298 | */
|
---|
| 299 | async embedLinkedStylesheet(link, compilation, outputPath, publicPath) {
|
---|
| 300 | const href = link.getAttribute('href');
|
---|
| 301 | const media = link.getAttribute('media');
|
---|
| 302 | const document = link.ownerDocument;
|
---|
| 303 |
|
---|
| 304 | const preloadMode = this.options.preload;
|
---|
| 305 |
|
---|
| 306 | // skip filtered resources, or network resources if no filter is provided
|
---|
| 307 | if (this.urlFilter ? this.urlFilter(href) : href.match(/^(https?:)?\/\//)) {
|
---|
| 308 | return Promise.resolve();
|
---|
| 309 | }
|
---|
| 310 |
|
---|
| 311 | // path on disk (with output.publicPath removed)
|
---|
| 312 | let normalizedPath = href.replace(/^\//, '');
|
---|
| 313 | const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/';
|
---|
| 314 | if (normalizedPath.indexOf(pathPrefix) === 0) {
|
---|
| 315 | normalizedPath = normalizedPath
|
---|
| 316 | .substring(pathPrefix.length)
|
---|
| 317 | .replace(/^\//, '');
|
---|
| 318 | }
|
---|
| 319 | const filename = path.resolve(outputPath, normalizedPath);
|
---|
| 320 |
|
---|
| 321 | // try to find a matching asset by filename in webpack's output (not yet written to disk)
|
---|
| 322 | const relativePath = path
|
---|
| 323 | .relative(outputPath, filename)
|
---|
| 324 | .replace(/^\.\//, '');
|
---|
| 325 | const asset = compilation.assets[relativePath];
|
---|
| 326 |
|
---|
| 327 | // Attempt to read from assets, falling back to a disk read
|
---|
| 328 | let sheet = asset && asset.source();
|
---|
| 329 | if (!sheet) {
|
---|
| 330 | try {
|
---|
| 331 | sheet = await this.readFile(compilation, filename);
|
---|
| 332 | this.logger.warn(
|
---|
| 333 | `Stylesheet "${relativePath}" not found in assets, but a file was located on disk.${
|
---|
| 334 | this.options.pruneSource
|
---|
| 335 | ? ' This means pruneSource will not be applied.'
|
---|
| 336 | : ''
|
---|
| 337 | }`
|
---|
| 338 | );
|
---|
| 339 | } catch (e) {
|
---|
| 340 | this.logger.warn(`Unable to locate stylesheet: ${relativePath}`);
|
---|
| 341 | return;
|
---|
| 342 | }
|
---|
| 343 | }
|
---|
| 344 |
|
---|
| 345 | // CSS loader is only injected for the first sheet, then this becomes an empty string
|
---|
| 346 | let cssLoaderPreamble = `function $loadcss(u,m,l){(l=document.createElement('link')).rel='stylesheet';l.href=u;document.head.appendChild(l)}`;
|
---|
| 347 | const lazy = preloadMode === 'js-lazy';
|
---|
| 348 | if (lazy) {
|
---|
| 349 | cssLoaderPreamble = cssLoaderPreamble.replace(
|
---|
| 350 | 'l.href',
|
---|
| 351 | `l.media='print';l.onload=function(){l.media=m};l.href`
|
---|
| 352 | );
|
---|
| 353 | }
|
---|
| 354 |
|
---|
| 355 | // the reduced critical CSS gets injected into a new <style> tag
|
---|
| 356 | const style = document.createElement('style');
|
---|
| 357 | style.appendChild(document.createTextNode(sheet));
|
---|
| 358 | link.parentNode.insertBefore(style, link);
|
---|
| 359 |
|
---|
| 360 | if (
|
---|
| 361 | this.options.inlineThreshold &&
|
---|
| 362 | sheet.length < this.options.inlineThreshold
|
---|
| 363 | ) {
|
---|
| 364 | style.$$reduce = false;
|
---|
| 365 | this.logger.info(
|
---|
| 366 | `\u001b[32mInlined all of ${href} (${sheet.length} was below the threshold of ${this.options.inlineThreshold})\u001b[39m`
|
---|
| 367 | );
|
---|
| 368 | if (asset) {
|
---|
| 369 | delete compilation.assets[relativePath];
|
---|
| 370 | } else {
|
---|
| 371 | this.logger.warn(
|
---|
| 372 | ` > ${href} was not found in assets. the resource may still be emitted but will be unreferenced.`
|
---|
| 373 | );
|
---|
| 374 | }
|
---|
| 375 | link.parentNode.removeChild(link);
|
---|
| 376 | return;
|
---|
| 377 | }
|
---|
| 378 |
|
---|
| 379 | // drop references to webpack asset locations onto the tag, used for later reporting and in-place asset updates
|
---|
| 380 | style.$$name = href;
|
---|
| 381 | style.$$asset = asset;
|
---|
| 382 | style.$$assetName = relativePath;
|
---|
| 383 | style.$$assets = compilation.assets;
|
---|
| 384 | style.$$links = [link];
|
---|
| 385 |
|
---|
| 386 | // Allow disabling any mutation of the stylesheet link:
|
---|
| 387 | if (preloadMode === false) return;
|
---|
| 388 |
|
---|
| 389 | let noscriptFallback = false;
|
---|
| 390 |
|
---|
| 391 | if (preloadMode === 'body') {
|
---|
| 392 | document.body.appendChild(link);
|
---|
| 393 | } else {
|
---|
| 394 | link.setAttribute('rel', 'preload');
|
---|
| 395 | link.setAttribute('as', 'style');
|
---|
| 396 | if (preloadMode === 'js' || preloadMode === 'js-lazy') {
|
---|
| 397 | const script = document.createElement('script');
|
---|
| 398 | const js = `${cssLoaderPreamble}$loadcss(${JSON.stringify(href)}${
|
---|
| 399 | lazy ? ',' + JSON.stringify(media || 'all') : ''
|
---|
| 400 | })`;
|
---|
| 401 | script.appendChild(document.createTextNode(js));
|
---|
| 402 | link.parentNode.insertBefore(script, link.nextSibling);
|
---|
| 403 | style.$$links.push(script);
|
---|
| 404 | cssLoaderPreamble = '';
|
---|
| 405 | noscriptFallback = true;
|
---|
| 406 | } else if (preloadMode === 'media') {
|
---|
| 407 | // @see https://github.com/filamentgroup/loadCSS/blob/af1106cfe0bf70147e22185afa7ead96c01dec48/src/loadCSS.js#L26
|
---|
| 408 | link.setAttribute('rel', 'stylesheet');
|
---|
| 409 | link.removeAttribute('as');
|
---|
| 410 | link.setAttribute('media', 'print');
|
---|
| 411 | link.setAttribute('onload', `this.media='${media || 'all'}'`);
|
---|
| 412 | noscriptFallback = true;
|
---|
| 413 | } else if (preloadMode === 'swap') {
|
---|
| 414 | link.setAttribute('onload', "this.rel='stylesheet'");
|
---|
| 415 | noscriptFallback = true;
|
---|
| 416 | } else {
|
---|
| 417 | const bodyLink = document.createElement('link');
|
---|
| 418 | bodyLink.setAttribute('rel', 'stylesheet');
|
---|
| 419 | if (media) bodyLink.setAttribute('media', media);
|
---|
| 420 | bodyLink.setAttribute('href', href);
|
---|
| 421 | document.body.appendChild(bodyLink);
|
---|
| 422 | style.$$links.push(bodyLink);
|
---|
| 423 | }
|
---|
| 424 | }
|
---|
| 425 |
|
---|
| 426 | if (this.options.noscriptFallback !== false && noscriptFallback) {
|
---|
| 427 | const noscript = document.createElement('noscript');
|
---|
| 428 | const noscriptLink = document.createElement('link');
|
---|
| 429 | noscriptLink.setAttribute('rel', 'stylesheet');
|
---|
| 430 | noscriptLink.setAttribute('href', href);
|
---|
| 431 | if (media) noscriptLink.setAttribute('media', media);
|
---|
| 432 | noscript.appendChild(noscriptLink);
|
---|
| 433 | link.parentNode.insertBefore(noscript, link.nextSibling);
|
---|
| 434 | style.$$links.push(noscript);
|
---|
| 435 | }
|
---|
| 436 | }
|
---|
| 437 |
|
---|
| 438 | /**
|
---|
| 439 | * Parse the stylesheet within a <style> element, then reduce it to contain only rules used by the document.
|
---|
| 440 | */
|
---|
| 441 | async processStyle(style) {
|
---|
| 442 | if (style.$$reduce === false) return;
|
---|
| 443 |
|
---|
| 444 | const name = style.$$name ? style.$$name.replace(/^\//, '') : 'inline CSS';
|
---|
| 445 | const options = this.options;
|
---|
| 446 | const document = style.ownerDocument;
|
---|
| 447 | const head = document.querySelector('head');
|
---|
| 448 | let keyframesMode = options.keyframes || 'critical';
|
---|
| 449 | // we also accept a boolean value for options.keyframes
|
---|
| 450 | if (keyframesMode === true) keyframesMode = 'all';
|
---|
| 451 | if (keyframesMode === false) keyframesMode = 'none';
|
---|
| 452 |
|
---|
| 453 | // basically `.textContent`
|
---|
| 454 | let sheet =
|
---|
| 455 | style.childNodes.length > 0 &&
|
---|
| 456 | [].map.call(style.childNodes, (node) => node.nodeValue).join('\n');
|
---|
| 457 |
|
---|
| 458 | // store a reference to the previous serialized stylesheet for reporting stats
|
---|
| 459 | const before = sheet;
|
---|
| 460 |
|
---|
| 461 | // Skip empty stylesheets
|
---|
| 462 | if (!sheet) return;
|
---|
| 463 |
|
---|
| 464 | const ast = parseStylesheet(sheet);
|
---|
| 465 | const astInverse = options.pruneSource ? parseStylesheet(sheet) : null;
|
---|
| 466 |
|
---|
| 467 | // a string to search for font names (very loose)
|
---|
| 468 | let criticalFonts = '';
|
---|
| 469 |
|
---|
| 470 | const failedSelectors = [];
|
---|
| 471 |
|
---|
| 472 | const criticalKeyframeNames = [];
|
---|
| 473 |
|
---|
| 474 | // Walk all CSS rules, marking unused rules with `.$$remove=true` for removal in the second pass.
|
---|
| 475 | // This first pass is also used to collect font and keyframe usage used in the second pass.
|
---|
| 476 | walkStyleRules(
|
---|
| 477 | ast,
|
---|
| 478 | markOnly((rule) => {
|
---|
| 479 | if (rule.type === 'rule') {
|
---|
| 480 | // Filter the selector list down to only those match
|
---|
| 481 | rule.filterSelectors((sel) => {
|
---|
| 482 | // Strip pseudo-elements and pseudo-classes, since we only care that their associated elements exist.
|
---|
| 483 | // This means any selector for a pseudo-element or having a pseudo-class will be inlined if the rest of the selector matches.
|
---|
| 484 | if (sel !== ':root') {
|
---|
| 485 | sel = sel.replace(/(?:>\s*)?::?[a-z-]+\s*(\{|$)/gi, '$1').trim();
|
---|
| 486 | }
|
---|
| 487 | if (!sel) return false;
|
---|
| 488 |
|
---|
| 489 | try {
|
---|
| 490 | return document.querySelector(sel) != null;
|
---|
| 491 | } catch (e) {
|
---|
| 492 | failedSelectors.push(sel + ' -> ' + e.message);
|
---|
| 493 | return false;
|
---|
| 494 | }
|
---|
| 495 | });
|
---|
| 496 | // If there are no matched selectors, remove the rule:
|
---|
| 497 | if (rule.selectors.length === 0) {
|
---|
| 498 | return false;
|
---|
| 499 | }
|
---|
| 500 |
|
---|
| 501 | if (rule.declarations) {
|
---|
| 502 | for (let i = 0; i < rule.declarations.length; i++) {
|
---|
| 503 | const decl = rule.declarations[i];
|
---|
| 504 |
|
---|
| 505 | // detect used fonts
|
---|
| 506 | if (decl.property && decl.property.match(/\bfont(-family)?\b/i)) {
|
---|
| 507 | criticalFonts += ' ' + decl.value;
|
---|
| 508 | }
|
---|
| 509 |
|
---|
| 510 | // detect used keyframes
|
---|
| 511 | if (
|
---|
| 512 | decl.property === 'animation' ||
|
---|
| 513 | decl.property === 'animation-name'
|
---|
| 514 | ) {
|
---|
| 515 | // @todo: parse animation declarations and extract only the name. for now we'll do a lazy match.
|
---|
| 516 | const names = decl.value.split(/\s+/);
|
---|
| 517 | for (let j = 0; j < names.length; j++) {
|
---|
| 518 | const name = names[j].trim();
|
---|
| 519 | if (name) criticalKeyframeNames.push(name);
|
---|
| 520 | }
|
---|
| 521 | }
|
---|
| 522 | }
|
---|
| 523 | }
|
---|
| 524 | }
|
---|
| 525 |
|
---|
| 526 | // keep font rules, they're handled in the second pass:
|
---|
| 527 | if (rule.type === 'font-face') return;
|
---|
| 528 |
|
---|
| 529 | // If there are no remaining rules, remove the whole rule:
|
---|
| 530 | const rules = rule.rules && rule.rules.filter((rule) => !rule.$$remove);
|
---|
| 531 | return !rules || rules.length !== 0;
|
---|
| 532 | })
|
---|
| 533 | );
|
---|
| 534 |
|
---|
| 535 | if (failedSelectors.length !== 0) {
|
---|
| 536 | this.logger.warn(
|
---|
| 537 | `${
|
---|
| 538 | failedSelectors.length
|
---|
| 539 | } rules skipped due to selector errors:\n ${failedSelectors.join(
|
---|
| 540 | '\n '
|
---|
| 541 | )}`
|
---|
| 542 | );
|
---|
| 543 | }
|
---|
| 544 |
|
---|
| 545 | const shouldPreloadFonts =
|
---|
| 546 | options.fonts === true || options.preloadFonts === true;
|
---|
| 547 | const shouldInlineFonts =
|
---|
| 548 | options.fonts !== false && options.inlineFonts === true;
|
---|
| 549 |
|
---|
| 550 | const preloadedFonts = [];
|
---|
| 551 | // Second pass, using data picked up from the first
|
---|
| 552 | walkStyleRulesWithReverseMirror(ast, astInverse, (rule) => {
|
---|
| 553 | // remove any rules marked in the first pass
|
---|
| 554 | if (rule.$$remove === true) return false;
|
---|
| 555 |
|
---|
| 556 | applyMarkedSelectors(rule);
|
---|
| 557 |
|
---|
| 558 | // prune @keyframes rules
|
---|
| 559 | if (rule.type === 'keyframes') {
|
---|
| 560 | if (keyframesMode === 'none') return false;
|
---|
| 561 | if (keyframesMode === 'all') return true;
|
---|
| 562 | return criticalKeyframeNames.indexOf(rule.name) !== -1;
|
---|
| 563 | }
|
---|
| 564 |
|
---|
| 565 | // prune @font-face rules
|
---|
| 566 | if (rule.type === 'font-face') {
|
---|
| 567 | let family, src;
|
---|
| 568 | for (let i = 0; i < rule.declarations.length; i++) {
|
---|
| 569 | const decl = rule.declarations[i];
|
---|
| 570 | if (decl.property === 'src') {
|
---|
| 571 | // @todo parse this properly and generate multiple preloads with type="font/woff2" etc
|
---|
| 572 | src = (decl.value.match(/url\s*\(\s*(['"]?)(.+?)\1\s*\)/) || [])[2];
|
---|
| 573 | } else if (decl.property === 'font-family') {
|
---|
| 574 | family = decl.value;
|
---|
| 575 | }
|
---|
| 576 | }
|
---|
| 577 |
|
---|
| 578 | if (src && shouldPreloadFonts && preloadedFonts.indexOf(src) === -1) {
|
---|
| 579 | preloadedFonts.push(src);
|
---|
| 580 | const preload = document.createElement('link');
|
---|
| 581 | preload.setAttribute('rel', 'preload');
|
---|
| 582 | preload.setAttribute('as', 'font');
|
---|
| 583 | preload.setAttribute('crossorigin', 'anonymous');
|
---|
| 584 | preload.setAttribute('href', src.trim());
|
---|
| 585 | head.appendChild(preload);
|
---|
| 586 | }
|
---|
| 587 |
|
---|
| 588 | // if we're missing info, if the font is unused, or if critical font inlining is disabled, remove the rule:
|
---|
| 589 | if (
|
---|
| 590 | !family ||
|
---|
| 591 | !src ||
|
---|
| 592 | criticalFonts.indexOf(family) === -1 ||
|
---|
| 593 | !shouldInlineFonts
|
---|
| 594 | ) {
|
---|
| 595 | return false;
|
---|
| 596 | }
|
---|
| 597 | }
|
---|
| 598 | });
|
---|
| 599 |
|
---|
| 600 | sheet = serializeStylesheet(ast, {
|
---|
| 601 | compress: this.options.compress !== false,
|
---|
| 602 | }).trim();
|
---|
| 603 |
|
---|
| 604 | // If all rules were removed, get rid of the style element entirely
|
---|
| 605 | if (sheet.trim().length === 0) {
|
---|
| 606 | if (style.parentNode) {
|
---|
| 607 | style.parentNode.removeChild(style);
|
---|
| 608 | }
|
---|
| 609 | return;
|
---|
| 610 | }
|
---|
| 611 |
|
---|
| 612 | let afterText = '';
|
---|
| 613 | if (options.pruneSource) {
|
---|
| 614 | const sheetInverse = serializeStylesheet(astInverse, {
|
---|
| 615 | compress: this.options.compress !== false,
|
---|
| 616 | });
|
---|
| 617 | const asset = style.$$asset;
|
---|
| 618 | if (asset) {
|
---|
| 619 | // if external stylesheet would be below minimum size, just inline everything
|
---|
| 620 | const minSize = this.options.minimumExternalSize;
|
---|
| 621 | if (minSize && sheetInverse.length < minSize) {
|
---|
| 622 | this.logger.info(
|
---|
| 623 | `\u001b[32mInlined all of ${name} (non-critical external stylesheet would have been ${sheetInverse.length}b, which was below the threshold of ${minSize})\u001b[39m`
|
---|
| 624 | );
|
---|
| 625 | setNodeText(style, before);
|
---|
| 626 | // remove any associated external resources/loaders:
|
---|
| 627 | if (style.$$links) {
|
---|
| 628 | for (const link of style.$$links) {
|
---|
| 629 | const parent = link.parentNode;
|
---|
| 630 | if (parent) parent.removeChild(link);
|
---|
| 631 | }
|
---|
| 632 | }
|
---|
| 633 | // delete the webpack asset:
|
---|
| 634 | delete style.$$assets[style.$$assetName];
|
---|
| 635 | return;
|
---|
| 636 | }
|
---|
| 637 |
|
---|
| 638 | const percent = (sheetInverse.length / before.length) * 100;
|
---|
| 639 | afterText = `, reducing non-inlined size ${
|
---|
| 640 | percent | 0
|
---|
| 641 | }% to ${prettyBytes(sheetInverse.length)}`;
|
---|
| 642 | style.$$assets[style.$$assetName] = new sources.LineToLineMappedSource(
|
---|
| 643 | sheetInverse,
|
---|
| 644 | style.$$assetName,
|
---|
| 645 | before
|
---|
| 646 | );
|
---|
| 647 | } else {
|
---|
| 648 | this.logger.warn(
|
---|
| 649 | 'pruneSource is enabled, but a style (' +
|
---|
| 650 | name +
|
---|
| 651 | ') has no corresponding Webpack asset.'
|
---|
| 652 | );
|
---|
| 653 | }
|
---|
| 654 | }
|
---|
| 655 |
|
---|
| 656 | // replace the inline stylesheet with its critical'd counterpart
|
---|
| 657 | setNodeText(style, sheet);
|
---|
| 658 |
|
---|
| 659 | // output stats
|
---|
| 660 | const percent = ((sheet.length / before.length) * 100) | 0;
|
---|
| 661 | this.logger.info(
|
---|
| 662 | '\u001b[32mInlined ' +
|
---|
| 663 | prettyBytes(sheet.length) +
|
---|
| 664 | ' (' +
|
---|
| 665 | percent +
|
---|
| 666 | '% of original ' +
|
---|
| 667 | prettyBytes(before.length) +
|
---|
| 668 | ') of ' +
|
---|
| 669 | name +
|
---|
| 670 | afterText +
|
---|
| 671 | '.\u001b[39m'
|
---|
| 672 | );
|
---|
| 673 | }
|
---|
| 674 | }
|
---|
| 675 |
|
---|
| 676 | // Original code picks 1 html and during prune removes CSS files from assets. What if theres another dependency
|
---|
| 677 | // Handle error when parsing stylesheet
|
---|
| 678 | // Most of our partner's CSS fails parsing
|
---|
| 679 | // JSDOM css parsing fails even when css.parse works
|
---|
| 680 |
|
---|