├── .editorconfig ├── .github └── workflows │ └── main.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── babel.config.js ├── package.json ├── packages ├── critters-webpack-plugin │ ├── README.md │ ├── package.json │ ├── src │ │ ├── index.js │ │ └── util.js │ └── test │ │ ├── __snapshots__ │ │ ├── index.test.js.snap │ │ └── standalone.test.js.snap │ │ ├── _helpers.js │ │ ├── fixtures │ │ ├── additionalStylesheets │ │ │ ├── additional.css │ │ │ ├── chunk.js │ │ │ ├── index.html │ │ │ ├── index.js │ │ │ └── style.css │ │ ├── basic │ │ │ ├── index.html │ │ │ └── index.js │ │ ├── external │ │ │ ├── index.html │ │ │ ├── index.js │ │ │ └── style.css │ │ ├── inlineThreshold │ │ │ ├── index.html │ │ │ ├── index.js │ │ │ └── style.css │ │ ├── keyframes │ │ │ ├── index.html │ │ │ ├── index.js │ │ │ └── style.css │ │ ├── raw │ │ │ ├── index.html │ │ │ └── index.js │ │ └── unused │ │ │ ├── index.html │ │ │ └── index.js │ │ ├── index.test.js │ │ └── standalone.test.js └── critters │ ├── README.md │ ├── package.json │ ├── src │ ├── css.js │ ├── dom.js │ ├── index.d.ts │ ├── index.js │ ├── text.css │ └── util.js │ └── test │ ├── __snapshots__ │ └── critters.test.js.snap │ ├── critters.test.js │ ├── security.test.js │ └── src │ ├── index.html │ ├── media-validation.html │ ├── styles.css │ ├── styles2.css │ └── subpath-validation.html └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - uses: actions/setup-node@v1 18 | with: 19 | node-version: 18 20 | - name: install, build, test 21 | run: | 22 | yarn --frozen-lockfile 23 | yarn build 24 | yarn test 25 | env: 26 | CI: true 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .DS_store 4 | next_sites 5 | coverage 6 | .vscode 7 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [v0.0.17](https://www.npmjs.com/package/critters/v/0.0.17) 2 | 3 | - Updated the HTML parser from parse5 to htmlparser2 4 | - Implemented caching to improve speed of matching class and id based selectors 5 | - Added option `includeSelectors` 6 | - Added option `reduceInlineStyles` 7 | 8 | Feature 9 | Include/Exclude CSS rules via comments in CSS 10 | 11 | Feature 12 | Adding Critters containers. Wrap the HTML contents in a `data-critters-container` container to indicate above the fold HTML. 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | 25 | ## Community Guidelines 26 | 27 | This project follows [Google's Open Source Community 28 | Guidelines](https://opensource.google.com/conduct/). 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2018 Google Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | packages/critters/README.md -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | [ 4 | '@babel/preset-env', 5 | { 6 | targets: { 7 | node: 'current' 8 | } 9 | } 10 | ] 11 | ] 12 | }; 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "critters-root", 3 | "private": true, 4 | "description": "Inline critical CSS and lazy-load the rest.", 5 | "license": "Apache-2.0", 6 | "author": "The Chromium Authors", 7 | "contributors": [ 8 | { 9 | "name": "Jason Miller", 10 | "email": "developit@google.com" 11 | }, 12 | { 13 | "name": "Janicklas Ralph", 14 | "email": "janicklas@google.com" 15 | } 16 | ], 17 | "workspaces": { 18 | "packages": [ 19 | "./packages/*" 20 | ], 21 | "nohoist": [ 22 | "**/css-loader", 23 | "**/file-loader", 24 | "**/mini-css-extract-plugin", 25 | "**/webpack" 26 | ] 27 | }, 28 | "scripts": { 29 | "build": "yarn workspaces run build", 30 | "build:main": "yarn workspace critters run build", 31 | "build:webpack": "yarn workspace critters-webpack-plugin run build", 32 | "docs": "yarn workspaces run docs", 33 | "release": "npm run build -s && git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags && npm publish", 34 | "test": "jest --coverage" 35 | }, 36 | "engines": { 37 | "node": ">=18.13.0", 38 | "yarn": ">=1.21.1 <2", 39 | "npm": "Please use yarn instead of NPM to install dependencies" 40 | }, 41 | "jest": { 42 | "testEnvironment": "node", 43 | "coverageReporters": [ 44 | "text" 45 | ], 46 | "moduleNameMapper": { 47 | "^critters$": "/packages/critters/src/index.js", 48 | "#(.*)": "/node_modules/$1" 49 | }, 50 | "collectCoverageFrom": [ 51 | "packages/*/src/**/*.js" 52 | ], 53 | "modulePaths": [ 54 | "/packages/critters-webpack-plugin/node_modules", 55 | "/packages/critters/node_modules" 56 | ], 57 | "watchPathIgnorePatterns": [ 58 | "node_modules", 59 | "dist" 60 | ], 61 | "transformIgnorePatterns": [] 62 | }, 63 | "prettier": { 64 | "singleQuote": true, 65 | "trailingComma": "none" 66 | }, 67 | "eslintConfig": { 68 | "extends": [ 69 | "standard", 70 | "plugin:jest/recommended", 71 | "prettier" 72 | ], 73 | "globals": { 74 | "document": "readonly", 75 | "DOMParser": "readonly" 76 | }, 77 | "parserOptions": { 78 | "ecmaFeatures": { 79 | "jsx": true, 80 | "modules": true 81 | } 82 | } 83 | }, 84 | "devDependencies": { 85 | "@babel/preset-env": "^7.11.0", 86 | "@types/jest": "^26.0.23", 87 | "babel-core": "^6.26.0", 88 | "babel-jest": "^26.3.0", 89 | "cheerio": "^1.0.0-rc.12", 90 | "eslint": "^7.6.0", 91 | "eslint-config-prettier": "^6.11.0", 92 | "eslint-config-standard": "^14.1.1", 93 | "eslint-plugin-import": "^2.11.0", 94 | "eslint-plugin-jest": "^23.20.0", 95 | "eslint-plugin-node": "^11.1.0", 96 | "eslint-plugin-promise": "^4.2.1", 97 | "eslint-plugin-standard": "^4.0.1", 98 | "jest": "^26.3.0", 99 | "jsdom": "^16.6.0", 100 | "microbundle": "^0.12.3", 101 | "prettier": "^2.3.0" 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/README.md: -------------------------------------------------------------------------------- 1 |

2 | critters-webpack-plugin 3 |

Critters Webpack plugin

4 |

5 | 6 | > critters-webpack-plugin inlines your app's [critical CSS] and lazy-loads the rest. 7 | 8 | ## critters-webpack-plugin [![npm](https://img.shields.io/npm/v/critters-webpack-plugin.svg?style=flat)](https://www.npmjs.org/package/critters-webpack-plugin) 9 | 10 | It's a little different from [other options](#similar-libraries), because it **doesn't use a headless browser** to render content. This tradeoff allows Critters to be very **fast and lightweight**. It also means Critters inlines all CSS rules used by your document, rather than only those needed for above-the-fold content. For alternatives, see [Similar Libraries](#similar-libraries). 11 | 12 | Critters' design makes it a good fit when inlining critical CSS for prerendered/SSR'd Single Page Applications. It was developed to be an excellent compliment to [prerender-loader](https://github.com/GoogleChromeLabs/prerender-loader), combining to dramatically improve first paint time for most Single Page Applications. 13 | 14 | ## Features 15 | 16 | * Fast - no browser, few dependencies 17 | * Integrates with [html-webpack-plugin] 18 | * Works with `webpack-dev-server` / `webpack serve` 19 | * Supports preloading and/or inlining critical fonts 20 | * Prunes unused CSS keyframes and media queries 21 | * Removes inlined CSS rules from lazy-loaded stylesheets 22 | 23 | ## Installation 24 | 25 | First, install Critters as a development dependency: 26 | 27 | ```sh 28 | npm i -D critters-webpack-plugin 29 | ``` 30 | 31 | Then, import Critters into your Webpack configuration and add it to your list of plugins: 32 | 33 | ```diff 34 | // webpack.config.js 35 | +const Critters = require('critters-webpack-plugin'); 36 | 37 | module.exports = { 38 | plugins: [ 39 | + new Critters({ 40 | + // optional configuration (see below) 41 | + }) 42 | ] 43 | } 44 | ``` 45 | 46 | That's it! Now when you run Webpack, the CSS used by your HTML will be inlined and the imports for your full CSS will be converted to load asynchronously. 47 | 48 | ## Usage 49 | 50 | 51 | 52 | ### CrittersWebpackPlugin 53 | 54 | **Extends Critters** 55 | 56 | Create a Critters plugin instance with the given options. 57 | 58 | #### Parameters 59 | 60 | * `options` **Options** Options to control how Critters inlines CSS. See 61 | 62 | #### Examples 63 | 64 | ```javascript 65 | // webpack.config.js 66 | module.exports = { 67 | plugins: [ 68 | new Critters({ 69 | // Outputs: 70 | preload: 'swap', 71 | 72 | // Don't inline critical font-face rules, but preload the font URLs: 73 | preloadFonts: true 74 | }) 75 | ] 76 | } 77 | ``` 78 | 79 | ## Similar Libraries 80 | 81 | There are a number of other libraries that can inline Critical CSS, each with a slightly different approach. Here are a few great options: 82 | 83 | * [Critical](https://github.com/addyosmani/critical) 84 | * [Penthouse](https://github.com/pocketjoso/penthouse) 85 | * [webpack-critical](https://github.com/lukeed/webpack-critical) 86 | * [webpack-plugin-critical](https://github.com/nrwl/webpack-plugin-critical) 87 | * [html-critical-webpack-plugin](https://github.com/anthonygore/html-critical-webpack-plugin) 88 | * [react-snap](https://github.com/stereobooster/react-snap) 89 | 90 | ## License 91 | 92 | [Apache 2.0](LICENSE) 93 | 94 | This is not an official Google product. 95 | 96 | [critical css]: https://www.smashingmagazine.com/2015/08/understanding-critical-css/ 97 | 98 | [html-webpack-plugin]: https://github.com/jantimon/html-webpack-plugin 99 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "critters-webpack-plugin", 3 | "version": "3.0.2", 4 | "description": "Webpack plugin to inline critical CSS and lazy-load the rest.", 5 | "main": "dist/critters-webpack-plugin.js", 6 | "module": "dist/critters-webpack-plugin.mjs", 7 | "source": "src/index.js", 8 | "exports": { 9 | "import": "./dist/critters-webpack-plugin.mjs", 10 | "require": "./dist/critters-webpack-plugin.js", 11 | "default": "./dist/critters-webpack-plugin.mjs" 12 | }, 13 | "files": [ 14 | "src", 15 | "dist" 16 | ], 17 | "license": "Apache-2.0", 18 | "author": "The Chromium Authors", 19 | "contributors": [ 20 | { 21 | "name": "Jason Miller", 22 | "email": "developit@google.com" 23 | }, 24 | { 25 | "name": "Janicklas Ralph", 26 | "email": "janicklas@google.com" 27 | } 28 | ], 29 | "keywords": [ 30 | "critical css", 31 | "inline css", 32 | "critical", 33 | "critters", 34 | "webpack plugin", 35 | "performance" 36 | ], 37 | "repository": { 38 | "type": "git", 39 | "url": "https://github.com/GoogleChromeLabs/critters", 40 | "directory": "packages/critters-webpack-plugin" 41 | }, 42 | "scripts": { 43 | "build": "microbundle --target node --no-sourcemap -f cjs,esm", 44 | "docs": "documentation readme -q --no-markdown-toc -a public -s Usage --sort-order alpha src", 45 | "prepare": "npm run -s build" 46 | }, 47 | "devDependencies": { 48 | "css-loader": "^4.2.1", 49 | "documentation": "^13.0.2", 50 | "file-loader": "^6.0.0", 51 | "html-webpack-plugin": "^4.5.2", 52 | "microbundle": "^0.12.3", 53 | "mini-css-extract-plugin": "^0.10.0", 54 | "webpack": "^4.46.0" 55 | }, 56 | "dependencies": { 57 | "critters": "^0.0.16", 58 | "minimatch": "^3.0.4", 59 | "webpack-log": "^3.0.1", 60 | "webpack-sources": "^1.3.0" 61 | }, 62 | "peerDependencies": { 63 | "html-webpack-plugin": "^4.5.2" 64 | }, 65 | "peerDependenciesMeta": { 66 | "html-webpack-plugin": { 67 | "optional": true 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/src/index.js: -------------------------------------------------------------------------------- 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 { createRequire } from 'module'; 19 | import minimatch from 'minimatch'; 20 | import sources from 'webpack-sources'; 21 | import log from 'webpack-log'; 22 | import Critters from 'critters'; 23 | import { tap } from './util'; 24 | 25 | const $require = 26 | typeof require !== 'undefined' 27 | ? require 28 | : createRequire(eval('import.meta.url')); 29 | 30 | // Used to annotate this plugin's hooks in Tappable invocations 31 | const PLUGIN_NAME = 'critters-webpack-plugin'; 32 | 33 | /** @typedef {import('critters').Options} Options */ 34 | 35 | /** 36 | * Create a Critters plugin instance with the given options. 37 | * @public 38 | * @param {Options} options Options to control how Critters inlines CSS. See https://github.com/GoogleChromeLabs/critters#usage 39 | * @example 40 | * // webpack.config.js 41 | * module.exports = { 42 | * plugins: [ 43 | * new Critters({ 44 | * // Outputs: 45 | * preload: 'swap', 46 | * 47 | * // Don't inline critical font-face rules, but preload the font URLs: 48 | * preloadFonts: true 49 | * }) 50 | * ] 51 | * } 52 | */ 53 | export default class CrittersWebpackPlugin extends Critters { 54 | constructor(options) { 55 | super(options); 56 | 57 | // TODO: Remove webpack-log 58 | this.logger = log({ 59 | name: 'Critters', 60 | unique: true, 61 | level: this.options.logLevel 62 | }); 63 | } 64 | 65 | /** 66 | * Invoked by Webpack during plugin initialization 67 | */ 68 | apply(compiler) { 69 | // hook into the compiler to get a Compilation instance... 70 | tap(compiler, 'compilation', PLUGIN_NAME, false, (compilation) => { 71 | this.options.path = compiler.options.output.path; 72 | this.options.publicPath = compiler.options.output.publicPath; 73 | 74 | const hasHtmlPlugin = compilation.options.plugins.find( 75 | (p) => p.constructor && p.constructor.name === 'HtmlWebpackPlugin' 76 | ); 77 | try { 78 | var htmlPluginHooks = $require('html-webpack-plugin').getHooks( 79 | compilation 80 | ); 81 | } catch (err) {} 82 | 83 | const handleHtmlPluginData = (htmlPluginData, callback) => { 84 | this.fs = compilation.outputFileSystem; 85 | this.compilation = compilation; 86 | this.process(htmlPluginData.html) 87 | .then((html) => { 88 | callback(null, { html }); 89 | }) 90 | .catch(callback); 91 | }; 92 | 93 | // get an "after" hook into html-webpack-plugin's HTML generation. 94 | if ( 95 | compilation.hooks && 96 | compilation.hooks.htmlWebpackPluginAfterHtmlProcessing 97 | ) { 98 | tap( 99 | compilation, 100 | 'html-webpack-plugin-after-html-processing', 101 | PLUGIN_NAME, 102 | true, 103 | handleHtmlPluginData 104 | ); 105 | } else if (hasHtmlPlugin && htmlPluginHooks) { 106 | htmlPluginHooks.beforeEmit.tapAsync(PLUGIN_NAME, handleHtmlPluginData); 107 | } else { 108 | // If html-webpack-plugin isn't used, process the first HTML asset as an optimize step 109 | tap( 110 | compilation, 111 | 'optimize-assets', 112 | PLUGIN_NAME, 113 | true, 114 | (assets, callback) => { 115 | this.fs = compilation.outputFileSystem; 116 | this.compilation = compilation; 117 | 118 | let htmlAssetName; 119 | for (const name in assets) { 120 | if (name.match(/\.html$/)) { 121 | htmlAssetName = name; 122 | break; 123 | } 124 | } 125 | if (!htmlAssetName) { 126 | return callback(Error('Could not find HTML asset.')); 127 | } 128 | const html = assets[htmlAssetName].source(); 129 | if (!html) return callback(Error('Empty HTML asset.')); 130 | 131 | this.process(String(html)) 132 | .then((html) => { 133 | assets[htmlAssetName] = new sources.RawSource(html); 134 | callback(); 135 | }) 136 | .catch(callback); 137 | } 138 | ); 139 | } 140 | }); 141 | } 142 | 143 | /** 144 | * Given href, find the corresponding CSS asset 145 | */ 146 | async getCssAsset(href, style) { 147 | const outputPath = this.options.path; 148 | const publicPath = this.options.publicPath; 149 | 150 | // CHECK - the output path 151 | // path on disk (with output.publicPath removed) 152 | let normalizedPath = href.replace(/^\//, ''); 153 | const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/'; 154 | if (normalizedPath.indexOf(pathPrefix) === 0) { 155 | normalizedPath = normalizedPath 156 | .substring(pathPrefix.length) 157 | .replace(/^\//, ''); 158 | } 159 | const filename = path.resolve(outputPath, normalizedPath); 160 | 161 | // try to find a matching asset by filename in webpack's output (not yet written to disk) 162 | const relativePath = path 163 | .relative(outputPath, filename) 164 | .replace(/^\.\//, ''); 165 | const asset = this.compilation.assets[relativePath]; // compilation.assets[relativePath]; 166 | 167 | // Attempt to read from assets, falling back to a disk read 168 | let sheet = asset && asset.source(); 169 | 170 | if (!sheet) { 171 | try { 172 | sheet = await this.readFile(this.compilation, filename); 173 | this.logger.warn( 174 | `Stylesheet "${relativePath}" not found in assets, but a file was located on disk.${ 175 | this.options.pruneSource 176 | ? ' This means pruneSource will not be applied.' 177 | : '' 178 | }` 179 | ); 180 | } catch (e) { 181 | this.logger.warn(`Unable to locate stylesheet: ${relativePath}`); 182 | return; 183 | } 184 | } 185 | 186 | style.$$asset = asset; 187 | style.$$assetName = relativePath; 188 | // style.$$assets = this.compilation.assets; 189 | 190 | return sheet; 191 | } 192 | 193 | checkInlineThreshold(link, style, sheet) { 194 | const inlined = super.checkInlineThreshold(link, style, sheet); 195 | 196 | if (inlined) { 197 | const asset = style.$$asset; 198 | if (asset) { 199 | delete this.compilation.assets[style.$$assetName]; 200 | } else { 201 | this.logger.warn( 202 | ` > ${style.$$name} was not found in assets. the resource may still be emitted but will be unreferenced.` 203 | ); 204 | } 205 | } 206 | 207 | return inlined; 208 | } 209 | 210 | /** 211 | * Inline the stylesheets from options.additionalStylesheets (assuming it passes `options.filter`) 212 | */ 213 | async embedAdditionalStylesheet(document) { 214 | const styleSheetsIncluded = []; 215 | (this.options.additionalStylesheets || []).forEach((cssFile) => { 216 | if (styleSheetsIncluded.includes(cssFile)) { 217 | return; 218 | } 219 | styleSheetsIncluded.push(cssFile); 220 | const webpackCssAssets = Object.keys(this.compilation.assets).filter( 221 | (file) => minimatch(file, cssFile) 222 | ); 223 | webpackCssAssets.map((asset) => { 224 | const style = document.createElement('style'); 225 | style.$$external = true; 226 | style.textContent = this.compilation.assets[asset].source(); 227 | document.head.appendChild(style); 228 | }); 229 | }); 230 | } 231 | 232 | /** 233 | * Prune the source CSS files 234 | */ 235 | pruneSource(style, before, sheetInverse) { 236 | const isStyleInlined = super.pruneSource(style, before, sheetInverse); 237 | const asset = style.$$asset; 238 | const name = style.$$name; 239 | 240 | if (asset) { 241 | // if external stylesheet would be below minimum size, just inline everything 242 | const minSize = this.options.minimumExternalSize; 243 | if (minSize && sheetInverse.length < minSize) { 244 | // delete the webpack asset: 245 | delete this.compilation.assets[style.$$assetName]; 246 | return true; 247 | } 248 | this.compilation.assets[style.$$assetName] = 249 | new sources.LineToLineMappedSource( 250 | sheetInverse, 251 | style.$$assetName, 252 | before 253 | ); 254 | } else { 255 | this.logger.warn( 256 | 'pruneSource is enabled, but a style (' + 257 | name + 258 | ') has no corresponding Webpack asset.' 259 | ); 260 | } 261 | 262 | return isStyleInlined; 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/src/util.js: -------------------------------------------------------------------------------- 1 | export function tap(inst, hook, pluginName, async, callback) { 2 | if (inst.hooks) { 3 | const camel = hook.replace(/-([a-z])/g, (s, i) => i.toUpperCase()); 4 | inst.hooks[camel][async ? 'tapAsync' : 'tap'](pluginName, callback); 5 | } else { 6 | inst.plugin(hook, callback); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/__snapshots__/index.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`External CSS should match snapshot 1`] = ` 4 | " 5 | 6 | 7 | External CSS Demo 8 | 57 | 58 | 66 |

My first styled page

67 |

Welcome to my styled page!

68 |
Made 5 April 2004
69 | 70 | 71 | " 72 | `; 73 | 74 | exports[`External CSS should prune external sheet 1`] = ` 75 | " 76 | .extra-style { 77 | font-size: 200%; 78 | } 79 | 80 | " 81 | `; 82 | 83 | exports[`Inline 150 | 151 | 152 | 160 |

My first styled page

161 |

Welcome to my styled page!

162 |
Made 5 April 2004
163 | 164 | 165 | " 166 | `; 167 | 168 | exports[`options { additionalStylesheets:["*.css"] } should match snapshot 1`] = ` 169 | " 170 | 171 | 172 | Additional Stylesheet CSS Demo 173 | 186 | 187 | 195 |

My first styled page

196 |

Welcome to my styled page!

197 |
Made 5 April 2004
198 | 199 | 200 | " 201 | `; 202 | 203 | exports[`options { async:true } should match snapshot 1`] = ` 204 | " 205 | 206 | 207 | External CSS Demo 208 | 257 | 258 | 266 |

My first styled page

267 |

Welcome to my styled page!

268 |
Made 5 April 2004
269 | 270 | 271 | " 272 | `; 273 | 274 | exports[`publicPath should match snapshot 1`] = ` 275 | " 276 | 277 | 278 | External CSS Demo 279 | 328 | 329 | 337 |

My first styled page

338 |

Welcome to my styled page!

339 |
Made 5 April 2004
340 | 341 | 342 | " 343 | `; 344 | 345 | exports[`publicPath should prune external sheet 1`] = ` 346 | " 347 | .extra-style { 348 | font-size: 200%; 349 | } 350 | 351 | " 352 | `; 353 | 354 | exports[`webpack compilation 1`] = ` 355 | " 356 | 357 | 358 | Basic Demo 359 | 419 | 420 | 421 | 429 |

My first styled page

430 |

Welcome to my styled page!

431 |
Made 5 April 2004
432 | 433 | 434 | " 435 | `; 436 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/__snapshots__/standalone.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Usage without html-webpack-plugin should process the first html asset 1`] = ` 4 | " 5 | h1 { 6 | color: green; 7 | } 8 | " 9 | `; 10 | 11 | exports[`Usage without html-webpack-plugin should process the first html asset 2`] = ` 12 | " 13 | 14 | 15 | Basic Demo 16 | 17 | 22 | 23 | 24 |

Some HTML Here

25 | 26 | 27 | " 28 | `; 29 | 30 | exports[`webpack compilation 1`] = ` 31 | " 32 | 33 | 34 | Basic Demo 35 | 41 | 46 | 47 | 48 |

Some HTML Here

49 | 50 | 51 | " 52 | `; 53 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/_helpers.js: -------------------------------------------------------------------------------- 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 { promisify } from 'util'; 18 | import fs from 'fs'; 19 | import path from 'path'; 20 | import webpack from 'webpack'; 21 | import { JSDOM } from 'jsdom'; 22 | import CrittersWebpackPlugin from '../src/index.js'; 23 | 24 | const { window } = new JSDOM(); 25 | 26 | // parse a string into a JSDOM Document 27 | export const parseDom = (html) => 28 | new window.DOMParser().parseFromString(html, 'text/html'); 29 | 30 | // returns a promise resolving to the contents of a file 31 | export const readFile = (file) => 32 | promisify(fs.readFile)(path.resolve(__dirname, file), 'utf8'); 33 | 34 | // invoke webpack on a given entry module, optionally mutating the default configuration 35 | export function compile(entry, configDecorator) { 36 | return new Promise((resolve, reject) => { 37 | const context = path.dirname(path.resolve(__dirname, entry)); 38 | entry = path.basename(entry); 39 | let config = { 40 | context, 41 | entry: path.resolve(context, entry), 42 | output: { 43 | path: path.resolve(__dirname, path.resolve(context, 'dist')), 44 | filename: 'bundle.js', 45 | chunkFilename: '[name].chunk.js' 46 | }, 47 | resolveLoader: { 48 | modules: [path.resolve(__dirname, '../node_modules')] 49 | }, 50 | // Needed to resolve `Error: error:0308010C:digital envelope routines::unsupported` in webpack 4. 51 | // Should remove when we drop support for webpack 4. 52 | optimization: { 53 | minimizer: [] 54 | }, 55 | module: { 56 | rules: [] 57 | }, 58 | plugins: [] 59 | }; 60 | if (configDecorator) { 61 | config = configDecorator(config) || config; 62 | } 63 | 64 | webpack(config, (err, stats) => { 65 | if (err) return reject(err); 66 | const info = stats.toJson(); 67 | if (stats.hasErrors()) return reject(info.errors.join('\n')); 68 | resolve(info); 69 | }); 70 | }); 71 | } 72 | 73 | // invoke webpack via compile(), applying Critters to inline CSS and injecting `html` and `document` properties into the webpack build info. 74 | export async function compileToHtml( 75 | fixture, 76 | configDecorator, 77 | crittersOptions = {} 78 | ) { 79 | const info = await compile(`fixtures/${fixture}/index.js`, (config) => { 80 | config = configDecorator(config) || config; 81 | config.plugins.push( 82 | new CrittersWebpackPlugin({ 83 | pruneSource: true, 84 | compress: false, 85 | logLevel: 'silent', 86 | ...crittersOptions 87 | }) 88 | ); 89 | }); 90 | info.html = await readFile(`fixtures/${fixture}/dist/index.html`); 91 | info.document = parseDom(info.html); 92 | return info; 93 | } 94 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/additional.css: -------------------------------------------------------------------------------- 1 | .additional-style { 2 | font-size: 200%; 3 | } 4 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/chunk.js: -------------------------------------------------------------------------------- 1 | import './additional.css'; 2 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Additional Stylesheet CSS Demo 5 | 6 | 7 | 15 |

My first styled page

16 |

Welcome to my styled page!

17 |
Made 5 April 2004
18 | 19 | 20 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/index.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | 3 | document.body.appendChild(document.createTextNode('this counts as SSR')); 4 | 5 | import('./chunk.js').then(); 6 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | padding: 0px; 3 | } 4 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/basic/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Basic Demo 5 | 65 | 66 | 67 | 75 |

My first styled page

76 |

Welcome to my styled page!

77 |
Made 5 April 2004
78 | 79 | 80 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/basic/index.js: -------------------------------------------------------------------------------- 1 | document.body.appendChild(document.createTextNode('this counts as SSR')); 2 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/external/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | External CSS Demo 5 | 6 | 7 | 15 |

My first styled page

16 |

Welcome to my styled page!

17 |
Made 5 April 2004
18 | 19 | 20 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/external/index.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | 3 | document.body.appendChild(document.createTextNode('this counts as SSR')); 4 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/external/style.css: -------------------------------------------------------------------------------- 1 | :root { 2 | font-size: 10px; 3 | } 4 | html { 5 | height: 100%; 6 | } 7 | body { 8 | padding-left: 11em; 9 | font-family: 'Times New Roman', times, serif; 10 | color: purple; 11 | background-color: #d8da3d; 12 | } 13 | *,:after,:before{ 14 | box-sizing: inherit 15 | } 16 | ul.navbar { 17 | list-style-type: none; 18 | padding: 0; 19 | margin: 0; 20 | position: absolute; 21 | top: 2em; 22 | left: 1em; 23 | width: 9em; 24 | } 25 | h1 { 26 | font-family: helvetica, arial, sans-serif; 27 | } 28 | ul.navbar li { 29 | background: white; 30 | margin: 0.5em 0; 31 | padding: 0.3em; 32 | border-right: 1em solid black; 33 | } 34 | ul.navbar a { 35 | text-decoration: none; 36 | } 37 | a:link { 38 | color: blue; 39 | } 40 | a:visited { 41 | color: purple; 42 | } 43 | footer { 44 | margin-top: 1em; 45 | padding-top: 1em; 46 | border-top: thin dotted; 47 | } 48 | .extra-style { 49 | font-size: 200%; 50 | } 51 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/inlineThreshold/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | inlineThreshold CSS Demo 5 | 6 | 7 | 15 |

My first styled page

16 |

Welcome to my styled page!

17 |
Made 5 April 2004
18 | 19 | 20 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/inlineThreshold/index.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | 3 | document.body.appendChild(document.createTextNode('this counts as SSR')); 4 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/inlineThreshold/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-left: 11em; 3 | font-family: "Times New Roman", times, serif; 4 | color: purple; 5 | background-color: #d8da3d; 6 | } 7 | ul.navbar { 8 | list-style-type: none; 9 | padding: 0; 10 | margin: 0; 11 | position: absolute; 12 | top: 2em; 13 | left: 1em; 14 | width: 9em; 15 | } 16 | h1 { 17 | font-family: helvetica, arial, sans-serif; 18 | } 19 | ul.navbar li { 20 | background: white; 21 | margin: 0.5em 0; 22 | padding: 0.3em; 23 | border-right: 1em solid black; 24 | } 25 | ul.navbar a { 26 | text-decoration: none; 27 | } 28 | a:link { 29 | color: blue; 30 | } 31 | a:visited { 32 | color: purple; 33 | } 34 | footer { 35 | margin-top: 1em; 36 | padding-top: 1em; 37 | border-top: thin dotted; 38 | } 39 | .extra-style { 40 | font-size: 200%; 41 | } 42 | 43 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/keyframes/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Keyframes Demo 5 | 6 | 7 |
8 | 9 | 10 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/keyframes/index.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | 3 | document.body.appendChild(document.createTextNode('this counts as SSR')); 4 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/keyframes/style.css: -------------------------------------------------------------------------------- 1 | .present { 2 | animation: present 100ms ease forwards 1; 3 | } 4 | @keyframes present { 5 | 0% { opacity: 0; } 6 | } 7 | 8 | .not-present { 9 | will-change: transform; 10 | animation-duration: 5s; 11 | animation-name: not-present; 12 | animation-timing-function: ease; 13 | } 14 | @keyframes not-present { 15 | from { transform: scale(0.001); } 16 | to { transform: scale(1); } 17 | } 18 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/raw/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Basic Demo 5 | 11 | 16 | 17 | 18 |

Some HTML Here

19 | 20 | 21 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/raw/index.js: -------------------------------------------------------------------------------- 1 | import html from './index.html'; 2 | 3 | module.exports = html; 4 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/unused/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Basic Demo 5 | 11 | 26 | 27 | 28 |

Some HTML Here

29 | 30 | 31 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/unused/index.js: -------------------------------------------------------------------------------- 1 | console.log('empty file'); 2 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/index.test.js: -------------------------------------------------------------------------------- 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 MiniCssExtractPlugin from 'mini-css-extract-plugin'; 18 | import HtmlWebpackPlugin from 'html-webpack-plugin'; 19 | import { compile, compileToHtml, readFile } from './_helpers.js'; 20 | 21 | function configure(config) { 22 | config.module.rules.push({ 23 | test: /\.css$/, 24 | use: [MiniCssExtractPlugin.loader, 'css-loader'] 25 | }); 26 | 27 | config.plugins.push( 28 | new MiniCssExtractPlugin({ 29 | filename: '[name].css', 30 | chunkFilename: '[name].chunk.css' 31 | }), 32 | new HtmlWebpackPlugin({ 33 | filename: 'index.html', 34 | template: 'index.html', 35 | inject: true, 36 | compile: true, 37 | minify: false 38 | }) 39 | ); 40 | } 41 | 42 | test('webpack compilation', async () => { 43 | const info = await compile('fixtures/basic/index.js', configure); 44 | expect(info.assets).toHaveLength(2); 45 | 46 | const html = await readFile('fixtures/basic/dist/index.html'); 47 | expect(html).toMatchSnapshot(); 48 | 49 | expect(html).toMatch(/\.extra-style/); 50 | }); 51 | 52 | describe('Inline 54 |
I'm Blue
55 | `; 56 | 57 | const inlined = await critters.process(html); 58 | 59 | console.log(inlined); 60 | // "
I'm Blue
" 61 | ``` 62 | 63 | ## Usage with webpack 64 | 65 | Critters is also available as a Webpack plugin called [critters-webpack-plugin](https://www.npmjs.org/package/critters-webpack-plugin). [![npm](https://img.shields.io/npm/v/critters-webpack-plugin.svg)](https://www.npmjs.org/package/critters-webpack-plugin) 66 | 67 | The Webpack plugin supports the same configuration options as the main `critters` package: 68 | 69 | ```diff 70 | // webpack.config.js 71 | +const Critters = require('critters-webpack-plugin'); 72 | 73 | module.exports = { 74 | plugins: [ 75 | + new Critters({ 76 | + // optional configuration 77 | + preload: 'swap', 78 | + includeSelectors: [/^\.btn/, '.banner'], 79 | + }) 80 | ] 81 | } 82 | ``` 83 | 84 | That's it! The resultant html will have its critical CSS inlined and the stylesheets lazy-loaded. 85 | 86 | ## Usage 87 | 88 | 89 | 90 | ### Critters 91 | 92 | All optional. Pass them to `new Critters({ ... })`. 93 | 94 | #### Parameters 95 | 96 | - `options` 97 | 98 | #### Properties 99 | 100 | - `path` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Base path location of the CSS files _(default: `''`)_ 101 | - `publicPath` **[String](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** Public path of the CSS resources. This prefix is removed from the href _(default: `''`)_ 102 | - `external` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Inline styles from external stylesheets _(default: `true`)_ 103 | - `inlineThreshold` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** Inline external stylesheets smaller than a given size _(default: `0`)_ 104 | - `minimumExternalSize` **[Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** If the non-critical external stylesheet would be below this size, just inline it _(default: `0`)_ 105 | - `pruneSource` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Remove inlined rules from the external stylesheet _(default: `false`)_ 106 | - `mergeStylesheets` **[Boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** Merged inlined stylesheets into a single `')) { 44 | return; 45 | } 46 | 47 | if (!options.compress) { 48 | cssStr += result; 49 | return; 50 | } 51 | 52 | // Simple minification logic 53 | if (node?.type === 'comment') return; 54 | 55 | if (node?.type === 'decl') { 56 | const prefix = node.prop + node.raws.between; 57 | 58 | cssStr += result.replace(prefix, prefix.trim()); 59 | return; 60 | } 61 | 62 | if (type === 'start') { 63 | if (node.type === 'rule' && node.selectors) { 64 | cssStr += node.selectors.join(',') + '{'; 65 | } else { 66 | cssStr += result.replace(/\s\{$/, '{'); 67 | } 68 | return; 69 | } 70 | 71 | if (type === 'end' && result === '}' && node?.raws?.semicolon) { 72 | cssStr = cssStr.slice(0, -1); 73 | } 74 | 75 | cssStr += result.trim(); 76 | }); 77 | 78 | return cssStr; 79 | } 80 | 81 | /** 82 | * Converts a walkStyleRules() iterator to mark nodes with `.$$remove=true` instead of actually removing them. 83 | * This means they can be removed in a second pass, allowing the first pass to be nondestructive (eg: to preserve mirrored sheets). 84 | * @private 85 | * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node. 86 | * @returns {(rule) => void} nonDestructiveIterator 87 | */ 88 | export function markOnly(predicate) { 89 | return (rule) => { 90 | const sel = rule.selectors; 91 | if (predicate(rule) === false) { 92 | rule.$$remove = true; 93 | } 94 | rule.$$markedSelectors = rule.selectors; 95 | if (rule._other) { 96 | rule._other.$$markedSelectors = rule._other.selectors; 97 | } 98 | rule.selectors = sel; 99 | }; 100 | } 101 | 102 | /** 103 | * Apply filtered selectors to a rule from a previous markOnly run. 104 | * @private 105 | * @param {css.Rule} rule The Rule to apply marked selectors to (if they exist). 106 | */ 107 | export function applyMarkedSelectors(rule) { 108 | if (rule.$$markedSelectors) { 109 | rule.selectors = rule.$$markedSelectors; 110 | } 111 | if (rule._other) { 112 | applyMarkedSelectors(rule._other); 113 | } 114 | } 115 | 116 | /** 117 | * Recursively walk all rules in a stylesheet. 118 | * @private 119 | * @param {css.Rule} node A Stylesheet or Rule to descend into. 120 | * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node. 121 | */ 122 | export function walkStyleRules(node, iterator) { 123 | node.nodes = node.nodes.filter((rule) => { 124 | if (hasNestedRules(rule)) { 125 | walkStyleRules(rule, iterator); 126 | } 127 | rule._other = undefined; 128 | rule.filterSelectors = filterSelectors; 129 | return iterator(rule) !== false; 130 | }); 131 | } 132 | 133 | /** 134 | * Recursively walk all rules in two identical stylesheets, filtering nodes into one or the other based on a predicate. 135 | * @private 136 | * @param {css.Rule} node A Stylesheet or Rule to descend into. 137 | * @param {css.Rule} node2 A second tree identical to `node` 138 | * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node from the first tree, true to remove it from the second. 139 | */ 140 | export function walkStyleRulesWithReverseMirror(node, node2, iterator) { 141 | if (node2 === null) return walkStyleRules(node, iterator); 142 | 143 | [node.nodes, node2.nodes] = splitFilter( 144 | node.nodes, 145 | node2.nodes, 146 | (rule, index, rules, rules2) => { 147 | const rule2 = rules2[index]; 148 | if (hasNestedRules(rule)) { 149 | walkStyleRulesWithReverseMirror(rule, rule2, iterator); 150 | } 151 | rule._other = rule2; 152 | rule.filterSelectors = filterSelectors; 153 | return iterator(rule) !== false; 154 | } 155 | ); 156 | } 157 | 158 | // Checks if a node has nested rules, like @media 159 | // @keyframes are an exception since they are evaluated as a whole 160 | function hasNestedRules(rule) { 161 | return ( 162 | rule.nodes?.length && 163 | rule.name !== 'keyframes' && 164 | rule.name !== '-webkit-keyframes' && 165 | rule.nodes.some((n) => n.type === 'rule' || n.type === 'atrule') 166 | ); 167 | } 168 | 169 | // Like [].filter(), but applies the opposite filtering result to a second copy of the Array without a second pass. 170 | // This is just a quicker version of generating the compliment of the set returned from a filter operation. 171 | function splitFilter(a, b, predicate) { 172 | const aOut = []; 173 | const bOut = []; 174 | for (let index = 0; index < a.length; index++) { 175 | if (predicate(a[index], index, a, b)) { 176 | aOut.push(a[index]); 177 | } else { 178 | bOut.push(a[index]); 179 | } 180 | } 181 | return [aOut, bOut]; 182 | } 183 | 184 | // can be invoked on a style rule to subset its selectors (with reverse mirroring) 185 | function filterSelectors(predicate) { 186 | if (this._other) { 187 | const [a, b] = splitFilter( 188 | this.selectors, 189 | this._other.selectors, 190 | predicate 191 | ); 192 | this.selectors = a; 193 | this._other.selectors = b; 194 | } else { 195 | this.selectors = this.selectors.filter(predicate); 196 | } 197 | } 198 | 199 | const MEDIA_TYPES = new Set(['all', 'print', 'screen', 'speech']); 200 | const MEDIA_KEYWORDS = new Set(['and', 'not', ',']); 201 | const MEDIA_FEATURES = new Set( 202 | [ 203 | 'width', 204 | 'aspect-ratio', 205 | 'color', 206 | 'color-index', 207 | 'grid', 208 | 'height', 209 | 'monochrome', 210 | 'orientation', 211 | 'resolution', 212 | 'scan' 213 | ].flatMap((feature) => [feature, `min-${feature}`, `max-${feature}`]) 214 | ); 215 | 216 | function validateMediaType(node) { 217 | const { type: nodeType, value: nodeValue } = node; 218 | if (nodeType === 'media-type') { 219 | return MEDIA_TYPES.has(nodeValue); 220 | } else if (nodeType === 'keyword') { 221 | return MEDIA_KEYWORDS.has(nodeValue); 222 | } else if (nodeType === 'media-feature') { 223 | return MEDIA_FEATURES.has(nodeValue); 224 | } 225 | } 226 | 227 | /** 228 | * 229 | * @param {string} Media query to validate 230 | * @returns {boolean} 231 | * 232 | * This function performs a basic media query validation 233 | * to ensure the values passed as part of the 'media' config 234 | * is HTML safe and does not cause any injection issue 235 | */ 236 | export function validateMediaQuery(query) { 237 | // The below is needed for consumption with webpack. 238 | const mediaParserFn = 'default' in mediaParser ? mediaParser.default : mediaParser; 239 | const mediaTree = mediaParserFn(query); 240 | const nodeTypes = new Set(['media-type', 'keyword', 'media-feature']); 241 | 242 | const stack = [mediaTree]; 243 | 244 | while (stack.length > 0) { 245 | const node = stack.pop(); 246 | 247 | if (nodeTypes.has(node.type) && !validateMediaType(node)) { 248 | return false; 249 | } 250 | 251 | if (node.nodes) { 252 | stack.push(...node.nodes); 253 | } 254 | } 255 | 256 | return true; 257 | } 258 | -------------------------------------------------------------------------------- /packages/critters/src/dom.js: -------------------------------------------------------------------------------- 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 { selectAll, selectOne } from 'css-select'; 18 | import { parseDocument, DomUtils } from 'htmlparser2'; 19 | import { parse as selectorParser } from 'css-what'; 20 | import { Element, Text } from 'domhandler'; 21 | import render from 'dom-serializer'; 22 | 23 | let classCache = null; 24 | let idCache = null; 25 | 26 | function buildCache(container) { 27 | classCache = new Set(); 28 | idCache = new Set(); 29 | const queue = [container]; 30 | 31 | while (queue.length) { 32 | const node = queue.shift(); 33 | 34 | if (node.hasAttribute('class')) { 35 | const classList = node.getAttribute('class').trim().split(' '); 36 | classList.forEach((cls) => { 37 | classCache.add(cls); 38 | }); 39 | } 40 | 41 | if (node.hasAttribute('id')) { 42 | const id = node.getAttribute('id').trim(); 43 | idCache.add(id); 44 | } 45 | 46 | queue.push(...node.children.filter((child) => child.type === 'tag')); 47 | } 48 | } 49 | 50 | /** 51 | * Parse HTML into a mutable, serializable DOM Document. 52 | * The DOM implementation is an htmlparser2 DOM enhanced with basic DOM mutation methods. 53 | * @param {String} html HTML to parse into a Document instance 54 | */ 55 | export function createDocument(html) { 56 | const document = /** @type {HTMLDocument} */ (parseDocument(html, {decodeEntities: false})); 57 | 58 | defineProperties(document, DocumentExtensions); 59 | 60 | // Extend Element.prototype with DOM manipulation methods. 61 | defineProperties(Element.prototype, ElementExtensions); 62 | 63 | // Critters container is the viewport to evaluate critical CSS 64 | let crittersContainer = document.querySelector('[data-critters-container]'); 65 | 66 | if (!crittersContainer) { 67 | document.documentElement.setAttribute('data-critters-container', ''); 68 | crittersContainer = document.documentElement; 69 | } 70 | 71 | document.crittersContainer = crittersContainer; 72 | buildCache(crittersContainer); 73 | 74 | return document; 75 | } 76 | 77 | /** 78 | * Serialize a Document to an HTML String 79 | * @param {HTMLDocument} document A Document, such as one created via `createDocument()` 80 | */ 81 | export function serializeDocument(document) { 82 | return render(document, { decodeEntities: false }); 83 | } 84 | 85 | /** @typedef {treeAdapter.Document & typeof ElementExtensions} HTMLDocument */ 86 | 87 | /** 88 | * Methods and descriptors to mix into Element.prototype 89 | * @private 90 | */ 91 | const ElementExtensions = { 92 | /** @extends treeAdapter.Element.prototype */ 93 | 94 | nodeName: { 95 | get() { 96 | return this.tagName.toUpperCase(); 97 | } 98 | }, 99 | 100 | id: reflectedProperty('id'), 101 | 102 | className: reflectedProperty('class'), 103 | 104 | insertBefore(child, referenceNode) { 105 | if (!referenceNode) return this.appendChild(child); 106 | DomUtils.prepend(referenceNode, child); 107 | return child; 108 | }, 109 | 110 | appendChild(child) { 111 | DomUtils.appendChild(this, child); 112 | return child; 113 | }, 114 | 115 | removeChild(child) { 116 | DomUtils.removeElement(child); 117 | }, 118 | 119 | remove() { 120 | DomUtils.removeElement(this); 121 | }, 122 | 123 | textContent: { 124 | get() { 125 | return DomUtils.getText(this); 126 | }, 127 | 128 | set(text) { 129 | this.children = []; 130 | DomUtils.appendChild(this, new Text(text)); 131 | } 132 | }, 133 | 134 | setAttribute(name, value) { 135 | if (this.attribs == null) this.attribs = {}; 136 | if (value == null) value = ''; 137 | this.attribs[name] = value; 138 | }, 139 | 140 | removeAttribute(name) { 141 | if (this.attribs != null) { 142 | delete this.attribs[name]; 143 | } 144 | }, 145 | 146 | getAttribute(name) { 147 | return this.attribs != null && this.attribs[name]; 148 | }, 149 | 150 | hasAttribute(name) { 151 | return this.attribs != null && this.attribs[name] != null; 152 | }, 153 | 154 | getAttributeNode(name) { 155 | const value = this.getAttribute(name); 156 | if (value != null) return { specified: true, value }; 157 | }, 158 | 159 | exists(sel) { 160 | return cachedQuerySelector(sel, this); 161 | }, 162 | 163 | querySelector(sel) { 164 | return selectOne(sel, this); 165 | }, 166 | 167 | querySelectorAll(sel) { 168 | return selectAll(sel, this); 169 | } 170 | }; 171 | 172 | /** 173 | * Methods and descriptors to mix into the global document instance 174 | * @private 175 | */ 176 | const DocumentExtensions = { 177 | /** @extends treeAdapter.Document.prototype */ 178 | 179 | // document is just an Element in htmlparser2, giving it a nodeType of ELEMENT_NODE. 180 | // TODO: verify if these are needed for css-select 181 | nodeType: { 182 | get() { 183 | return 9; 184 | } 185 | }, 186 | 187 | contentType: { 188 | get() { 189 | return 'text/html'; 190 | } 191 | }, 192 | 193 | nodeName: { 194 | get() { 195 | return '#document'; 196 | } 197 | }, 198 | 199 | documentElement: { 200 | get() { 201 | // Find the first element within the document 202 | return this.children.find( 203 | (child) => String(child.tagName).toLowerCase() === 'html' 204 | ); 205 | } 206 | }, 207 | 208 | head: { 209 | get() { 210 | return this.querySelector('head'); 211 | } 212 | }, 213 | 214 | body: { 215 | get() { 216 | return this.querySelector('body'); 217 | } 218 | }, 219 | 220 | createElement(name) { 221 | return new Element(name); 222 | }, 223 | 224 | createTextNode(text) { 225 | // there is no dedicated createTextNode equivalent exposed in htmlparser2's DOM 226 | return new Text(text); 227 | }, 228 | 229 | exists(sel) { 230 | return cachedQuerySelector(sel, this); 231 | }, 232 | 233 | querySelector(sel) { 234 | return selectOne(sel, this); 235 | }, 236 | 237 | querySelectorAll(sel) { 238 | if (sel === ':root') { 239 | return this; 240 | } 241 | return selectAll(sel, this); 242 | } 243 | }; 244 | 245 | /** 246 | * Essentially `Object.defineProperties()`, except function values are assigned as value descriptors for convenience. 247 | * @private 248 | */ 249 | function defineProperties(obj, properties) { 250 | for (const i in properties) { 251 | const value = properties[i]; 252 | Object.defineProperty( 253 | obj, 254 | i, 255 | typeof value === 'function' ? { value } : value 256 | ); 257 | } 258 | } 259 | 260 | /** 261 | * Create a property descriptor defining a getter/setter pair alias for a named attribute. 262 | * @private 263 | */ 264 | function reflectedProperty(attributeName) { 265 | return { 266 | get() { 267 | return this.getAttribute(attributeName); 268 | }, 269 | set(value) { 270 | this.setAttribute(attributeName, value); 271 | } 272 | }; 273 | } 274 | 275 | function cachedQuerySelector(sel, node) { 276 | const selectorTokens = selectorParser(sel); 277 | for (const tokens of selectorTokens) { 278 | // Check if the selector is a class selector 279 | if (tokens.length === 1) { 280 | const token = tokens[0]; 281 | if (token.type === 'attribute' && token.name === 'class') { 282 | return classCache.has(token.value); 283 | } 284 | if (token.type === 'attribute' && token.name === 'id') { 285 | return idCache.has(token.value); 286 | } 287 | } 288 | } 289 | return !!selectOne(sel, node); 290 | } 291 | -------------------------------------------------------------------------------- /packages/critters/src/index.d.ts: -------------------------------------------------------------------------------- 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 | export default class Critters { 18 | /** 19 | * Create an instance of Critters with custom options. 20 | * The `.process()` method can be called repeatedly to re-use this instance and its cache. 21 | */ 22 | constructor(options: Options); 23 | /** 24 | * Process an HTML document to inline critical CSS from its stylesheets. 25 | * @param {string} html String containing a full HTML document to be parsed. 26 | * @returns {string} A modified copy of the provided HTML with critical CSS inlined. 27 | */ 28 | process(html: string): Promise; 29 | /** 30 | * Read the contents of a file from the specified filesystem or disk. 31 | * Override this method to customize how stylesheets are loaded. 32 | */ 33 | readFile(filename: string): Promise | string; 34 | /** 35 | * Given a stylesheet URL, returns the corresponding CSS asset. 36 | * Overriding this method requires doing your own URL normalization, so it's generally better to override `readFile()`. 37 | */ 38 | getCssAsset(href: string): Promise | string | undefined; 39 | } 40 | 41 | export interface Options { 42 | path?: string; 43 | publicPath?: string; 44 | external?: boolean; 45 | inlineThreshold?: number; 46 | minimumExternalSize?: number; 47 | pruneSource?: boolean; 48 | mergeStylesheets?: boolean; 49 | additionalStylesheets?: string[]; 50 | preload?: 'body' | 'media' | 'swap' | 'js' | 'js-lazy'; 51 | noscriptFallback?: boolean; 52 | inlineFonts?: boolean; 53 | preloadFonts?: boolean; 54 | fonts?: boolean; 55 | keyframes?: string; 56 | compress?: boolean; 57 | logLevel?: 'info' | 'warn' | 'error' | 'trace' | 'debug' | 'silent'; 58 | reduceInlineStyles?: boolean; 59 | logger?: Logger; 60 | } 61 | 62 | export interface Logger { 63 | trace?: (message: string) => void; 64 | debug?: (message: string) => void; 65 | info?: (message: string) => void; 66 | warn?: (message: string) => void; 67 | error?: (message: string) => void; 68 | } 69 | -------------------------------------------------------------------------------- /packages/critters/src/index.js: -------------------------------------------------------------------------------- 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 { readFile } from 'fs'; 18 | import { createDocument, serializeDocument } from './dom'; 19 | import path from 'path'; 20 | import { 21 | applyMarkedSelectors, 22 | markOnly, 23 | parseStylesheet, 24 | serializeStylesheet, 25 | validateMediaQuery, 26 | walkStyleRules, 27 | walkStyleRulesWithReverseMirror 28 | } from './css'; 29 | import { createLogger, isSubpath } from './util'; 30 | 31 | /** 32 | * The mechanism to use for lazy-loading stylesheets. 33 | * 34 | * Note: JS indicates a strategy requiring JavaScript (falls back to `