├── README.md ├── packages ├── critters │ ├── test │ │ ├── src │ │ │ ├── styles2.css │ │ │ ├── index.html │ │ │ ├── subpath-validation.html │ │ │ ├── media-validation.html │ │ │ └── styles.css │ │ ├── security.test.js │ │ ├── __snapshots__ │ │ │ └── critters.test.js.snap │ │ └── critters.test.js │ ├── src │ │ ├── text.css │ │ ├── util.js │ │ ├── index.d.ts │ │ ├── dom.js │ │ ├── css.js │ │ └── index.js │ ├── package.json │ └── README.md └── critters-webpack-plugin │ ├── test │ ├── fixtures │ │ ├── unused │ │ │ ├── index.js │ │ │ └── index.html │ │ ├── additionalStylesheets │ │ │ ├── chunk.js │ │ │ ├── style.css │ │ │ ├── additional.css │ │ │ ├── index.js │ │ │ └── index.html │ │ ├── raw │ │ │ ├── index.js │ │ │ └── index.html │ │ ├── basic │ │ │ ├── index.js │ │ │ └── index.html │ │ ├── external │ │ │ ├── index.js │ │ │ ├── index.html │ │ │ └── style.css │ │ ├── keyframes │ │ │ ├── index.js │ │ │ ├── index.html │ │ │ └── style.css │ │ └── inlineThreshold │ │ │ ├── index.js │ │ │ ├── index.html │ │ │ └── style.css │ ├── __snapshots__ │ │ ├── standalone.test.js.snap │ │ └── index.test.js.snap │ ├── standalone.test.js │ ├── _helpers.js │ └── index.test.js │ ├── src │ ├── util.js │ └── index.js │ ├── package.json │ └── README.md ├── .gitignore ├── .editorconfig ├── babel.config.js ├── CHANGELOG.md ├── .github └── workflows │ └── main.yml ├── CONTRIBUTING.md ├── package.json └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | packages/critters/README.md -------------------------------------------------------------------------------- /packages/critters/test/src/styles2.css: -------------------------------------------------------------------------------- 1 | body { 2 | height: 100%; 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .DS_store 4 | next_sites 5 | coverage 6 | .vscode 7 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/unused/index.js: -------------------------------------------------------------------------------- 1 | console.log('empty file'); 2 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/chunk.js: -------------------------------------------------------------------------------- 1 | import './additional.css'; 2 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/fixtures/additionalStylesheets/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | padding: 0px; 3 | } 4 | -------------------------------------------------------------------------------- /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/additionalStylesheets/additional.css: -------------------------------------------------------------------------------- 1 | .additional-style { 2 | font-size: 200%; 3 | } 4 | -------------------------------------------------------------------------------- /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.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | 3 | document.body.appendChild(document.createTextNode('this counts as SSR')); 4 | -------------------------------------------------------------------------------- /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/inlineThreshold/index.js: -------------------------------------------------------------------------------- 1 | import './style.css'; 2 | 3 | document.body.appendChild(document.createTextNode('this counts as SSR')); 4 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/keyframes/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Keyframes Demo 5 | 6 | 7 |
8 | 9 | 10 | -------------------------------------------------------------------------------- /packages/critters/src/text.css: -------------------------------------------------------------------------------- 1 | @media screen and (min-width: 480px) { 2 | body { 3 | background-color: lightgreen; 4 | } 5 | } 6 | 7 | #main { 8 | border: 1px solid black; 9 | } 10 | 11 | ul li { 12 | padding: 5px; 13 | } 14 | 15 | @media print and alert('hellp') { 16 | padding: 5px; 17 | } 18 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /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 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /packages/critters/test/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Testing 4 | 5 | 6 | 7 |
8 |
9 | 10 |
11 |
12 |
13 |

Hello World!

14 |

This is a paragraph

15 | 16 |
17 |
18 |
19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /packages/critters/test/src/subpath-validation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Testing 4 | 5 | 6 | 7 | 8 |
9 |
10 | 11 |
12 |
13 |
14 |

Hello World!

15 |

This is a paragraph

16 | 17 |
18 |
19 |
20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /packages/critters/test/src/media-validation.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Testing 4 | 5 | 6 | 7 | 8 |
9 |
10 | 11 |
12 |
13 |
14 |

Hello World!

15 |

This is a paragraph

16 | 17 |
18 |
19 |
20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /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/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/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/src/util.js: -------------------------------------------------------------------------------- 1 | import chalk from 'chalk'; 2 | import path from 'path'; 3 | 4 | const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'silent']; 5 | 6 | export const defaultLogger = { 7 | trace(msg) { 8 | console.trace(msg); 9 | }, 10 | 11 | debug(msg) { 12 | console.debug(msg); 13 | }, 14 | 15 | warn(msg) { 16 | console.warn(chalk.yellow(msg)); 17 | }, 18 | 19 | error(msg) { 20 | console.error(chalk.bold.red(msg)); 21 | }, 22 | 23 | info(msg) { 24 | console.info(chalk.bold.blue(msg)); 25 | }, 26 | 27 | silent() {} 28 | }; 29 | 30 | export function createLogger(logLevel) { 31 | const logLevelIdx = LOG_LEVELS.indexOf(logLevel); 32 | 33 | return LOG_LEVELS.reduce((logger, type, index) => { 34 | if (index >= logLevelIdx) { 35 | logger[type] = defaultLogger[type]; 36 | } else { 37 | logger[type] = defaultLogger.silent; 38 | } 39 | return logger; 40 | }, {}); 41 | } 42 | 43 | export function isSubpath(basePath, currentPath) { 44 | return !path.relative(basePath, currentPath).startsWith('..'); 45 | } 46 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /packages/critters/test/src/styles.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | color: blue; 3 | } 4 | 5 | h2.unused { 6 | color: red; 7 | } 8 | 9 | p { 10 | color: purple; 11 | } 12 | 13 | p.unused { 14 | color: orange; 15 | } 16 | 17 | header { 18 | padding: 0 50px; 19 | } 20 | 21 | .banner { 22 | font-family: sans-serif; 23 | } 24 | 25 | .contents { 26 | padding: 50px; 27 | text-align: center; 28 | } 29 | 30 | .input-field { 31 | padding: 10px; 32 | } 33 | 34 | footer { 35 | margin-top: 10px; 36 | } 37 | 38 | /* critters:exclude */ 39 | .container { 40 | border: 1px solid; 41 | } 42 | 43 | /* critters:include */ 44 | .custom-element::part(tab) { 45 | color: #0c0dcc; 46 | border-bottom: transparent solid 2px; 47 | } 48 | 49 | /*! critters:include */ 50 | .other-element::part(tab) { 51 | color: #0c0dcc; 52 | border-bottom: transparent solid 2px; 53 | } 54 | 55 | .custom-element::part(tab):hover { 56 | background-color: #0c0d19; 57 | color: #ffffff; 58 | border-color: #0c0d33; 59 | } 60 | 61 | /* critters:include start */ 62 | .custom-element::part(tab):hover:active { 63 | background-color: #0c0d33; 64 | color: #ffffff; 65 | } 66 | 67 | .custom-element::part(tab):focus { 68 | box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff, 69 | 0 0 0 4px rgba(10, 132, 255, 0.3); 70 | } 71 | /* critters:include end */ 72 | 73 | .custom-element::part(active) { 74 | color: #0060df; 75 | border-color: #0a84ff !important; 76 | } 77 | 78 | div:is(:hover, .active) { 79 | color: #000; 80 | } 81 | 82 | div:is(.selected, :hover) { 83 | color: #fff; 84 | } 85 | -------------------------------------------------------------------------------- /packages/critters/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "critters", 3 | "version": "0.0.25", 4 | "description": "Inline critical CSS and lazy-load the rest.", 5 | "main": "dist/critters.js", 6 | "module": "dist/critters.mjs", 7 | "source": "src/index.js", 8 | "exports": { 9 | "import": "./dist/critters.mjs", 10 | "require": "./dist/critters.js", 11 | "default": "./dist/critters.mjs" 12 | }, 13 | "typings": "src/index.d.ts", 14 | "files": [ 15 | "src", 16 | "dist" 17 | ], 18 | "license": "Apache-2.0", 19 | "author": "The Chromium Authors", 20 | "contributors": [ 21 | { 22 | "name": "Jason Miller", 23 | "email": "developit@google.com" 24 | }, 25 | { 26 | "name": "Janicklas Ralph", 27 | "email": "janicklas@google.com" 28 | } 29 | ], 30 | "keywords": [ 31 | "critical css", 32 | "inline css", 33 | "critical", 34 | "critters", 35 | "webpack plugin", 36 | "performance" 37 | ], 38 | "repository": { 39 | "type": "git", 40 | "url": "https://github.com/GoogleChromeLabs/critters", 41 | "directory": "packages/critters" 42 | }, 43 | "scripts": { 44 | "build": "microbundle --target node --no-sourcemap -f cjs,esm", 45 | "docs": "documentation readme -q --no-markdown-toc -a public -s Usage --sort-order alpha src", 46 | "prepare": "npm run -s build" 47 | }, 48 | "dependencies": { 49 | "chalk": "^4.1.0", 50 | "css-select": "^5.1.0", 51 | "dom-serializer": "^2.0.0", 52 | "domhandler": "^5.0.2", 53 | "htmlparser2": "^8.0.2", 54 | "postcss": "^8.4.23", 55 | "postcss-media-query-parser": "^0.2.3" 56 | }, 57 | "devDependencies": { 58 | "documentation": "^13.0.2", 59 | "microbundle": "^0.12.3" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /packages/critters-webpack-plugin/test/standalone.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 { compile, compileToHtml, readFile } from './_helpers.js'; 18 | 19 | function configure(config) { 20 | config.module.rules.push( 21 | { 22 | test: /\.css$/, 23 | loader: 'css-loader' 24 | }, 25 | { 26 | test: /\.html$/, 27 | loader: 'file-loader?name=[name].[ext]' 28 | } 29 | ); 30 | } 31 | 32 | test('webpack compilation', async () => { 33 | const info = await compile('fixtures/raw/index.js', configure); 34 | expect(info.assets).toHaveLength(2); 35 | expect(await readFile('fixtures/raw/dist/index.html')).toMatchSnapshot(); 36 | }); 37 | 38 | describe('Usage without html-webpack-plugin', () => { 39 | let output; 40 | beforeAll(async () => { 41 | output = await compileToHtml('raw', configure); 42 | }); 43 | 44 | it('should process the first html asset', () => { 45 | const { html, document } = output; 46 | expect(document.querySelectorAll('style')).toHaveLength(1); 47 | expect(document.getElementById('unused')).toBeNull(); 48 | expect(document.getElementById('used')).not.toBeNull(); 49 | expect(document.getElementById('used').textContent).toMatchSnapshot(); 50 | expect(html).toMatchSnapshot(); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /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 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /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/test/security.test.js: -------------------------------------------------------------------------------- 1 | import Critters from '../src/index'; 2 | import * as cheerio from 'cheerio'; 3 | 4 | function hasEvilOnload(html) { 5 | const $ = cheerio.load(html, { scriptingEnabled: true }); 6 | return $('[onload]').attr('onload').includes(`''-alert(1)-''`); 7 | } 8 | 9 | function hasEvilScript(html) { 10 | const $ = cheerio.load(html, { scriptingEnabled: true }); 11 | const scripts = Array.from($('script')); 12 | return scripts.some((s) => s.textContent.trim() === 'alert(1)'); 13 | } 14 | 15 | describe('Critters', () => { 16 | it('should not decode entities', async () => { 17 | const critters = new Critters({}); 18 | const html = await critters.process(` 19 | 20 | 21 | <script>alert(1)</script> 22 | `); 23 | expect(hasEvilScript(html)).toBeFalsy(); 24 | }); 25 | it('should not create a new script tag from embedding linked stylesheets', async () => { 26 | const critters = new Critters({}); 27 | critters.readFile = () => 28 | `* { background: url('') }`; 29 | const html = await critters.process(` 30 | 31 | 32 | 33 | 34 | 35 | 36 | `); 37 | expect(hasEvilScript(html)).toBeFalsy(); 38 | }); 39 | it('should not create a new script tag from embedding additional stylesheets', async () => { 40 | const critters = new Critters({ 41 | additionalStylesheets: ['/style.css'] 42 | }); 43 | critters.readFile = () => 44 | `* { background: url('') }`; 45 | const html = await critters.process(` 46 | 47 | 48 | 49 | 50 | 51 | 52 | `); 53 | expect(hasEvilScript(html)).toBeFalsy(); 54 | }); 55 | 56 | it('should not create a new script tag by ending from href', async () => { 57 | const critters = new Critters({ preload: 'js' }); 58 | critters.readFile = () => `* { background: red }`; 59 | const html = await critters.process(` 60 | 61 | 62 | 63 | 64 | 65 | 66 | `); 67 | expect(hasEvilScript(html)).toBeFalsy(); 68 | }); 69 | }); 70 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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/test/__snapshots__/critters.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Critters Basic Usage 1`] = ` 4 | " 5 | 6 | 7 | 8 | 9 |

Hello World!

10 |

This is a paragraph

11 | 12 | " 13 | `; 14 | 15 | exports[`Critters Prevent injection via media attr 1`] = ` 16 | " 17 | 18 | Testing 19 | 21 | 22 | 23 | 24 |
25 |
26 |
Lorem ipsum dolor sit amet
27 |
28 |
29 |
30 |

Hello World!

31 |

This is a paragraph

32 | 33 |
34 |
35 |
36 |
37 | 38 | 39 | " 40 | `; 41 | 42 | exports[`Critters Run on HTML file 1`] = ` 43 | " 44 | 45 | Testing 46 | 48 | 49 | 50 |
51 |
52 |
Lorem ipsum dolor sit amet
53 |
54 |
55 |
56 |

Hello World!

57 |

This is a paragraph

58 | 59 |
60 |
61 |
62 |
63 | 64 | 65 | " 66 | `; 67 | 68 | exports[`Critters Skip invalid path 1`] = ` 69 | " 70 | 71 | Testing 72 | 74 | 75 | 76 | 77 |
78 |
79 |
Lorem ipsum dolor sit amet
80 |
81 |
82 |
83 |

Hello World!

84 |

This is a paragraph

85 | 86 |
87 |
88 |
89 |
90 | 91 | 92 | " 93 | `; 94 | 95 | exports[`Critters should keep existing link tag attributes 1`] = ` 96 | " 97 | 98 | $title 99 | 100 | 101 | 102 |

Hello World!

103 | 104 | " 105 | `; 106 | 107 | exports[`Critters should keep existing link tag attributes in the noscript link 1`] = ` 108 | " 109 | 110 | $title 111 | 112 | 113 | 114 |

Hello World!

115 | 116 | " 117 | `; 118 | -------------------------------------------------------------------------------- /packages/critters/test/critters.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 Critters from '../src/index'; 18 | import fs from 'fs'; 19 | import path from 'path'; 20 | 21 | const trim = (s) => 22 | s[0] 23 | .trim() 24 | .replace(new RegExp('^' + s[0].match(/^( {2}|\t)+/m)[0], 'gm'), ''); 25 | 26 | describe('Critters', () => { 27 | test('Basic Usage', async () => { 28 | const critters = new Critters({ 29 | reduceInlineStyles: false, 30 | path: '/' 31 | }); 32 | const assets = { 33 | '/style.css': trim` 34 | h1 { color: blue; } 35 | h2.unused { color: red; } 36 | p { color: purple; } 37 | p.unused { color: orange; } 38 | ` 39 | }; 40 | critters.readFile = (filename) => assets[filename]; 41 | const result = await critters.process(trim` 42 | 43 | 44 | 45 | 46 | 47 |

Hello World!

48 |

This is a paragraph

49 | 50 | 51 | `); 52 | expect(result).toMatch(''); 53 | expect(result).toMatch(''); 54 | expect(result).toMatchSnapshot(); 55 | }); 56 | 57 | test('Run on HTML file', async () => { 58 | const critters = new Critters({ 59 | reduceInlineStyles: false, 60 | path: path.join(__dirname, 'src') 61 | }); 62 | 63 | const html = fs.readFileSync( 64 | path.join(__dirname, 'src/index.html'), 65 | 'utf8' 66 | ); 67 | 68 | const result = await critters.process(html); 69 | expect(result).toMatchSnapshot(); 70 | }); 71 | 72 | test('Does not encode HTML', async () => { 73 | const critters = new Critters({ 74 | reduceInlineStyles: false, 75 | path: '/' 76 | }); 77 | const assets = { 78 | '/style.css': trim` 79 | h1 { color: blue; } 80 | ` 81 | }; 82 | critters.readFile = (filename) => assets[filename]; 83 | const result = await critters.process(trim` 84 | 85 | 86 | $title 87 | 88 | 89 | 90 |

Hello World!

91 | 92 | 93 | `); 94 | expect(result).toMatch(''); 95 | expect(result).toMatch(''); 96 | expect(result).toMatch('$title'); 97 | }); 98 | 99 | test('should keep existing link tag attributes in the noscript link', async () => { 100 | const critters = new Critters({ 101 | reduceInlineStyles: false, 102 | path: '/', 103 | preload: 'media' 104 | }); 105 | const assets = { 106 | '/style.css': trim` 107 | h1 { color: blue; } 108 | ` 109 | }; 110 | critters.readFile = (filename) => assets[filename]; 111 | const result = await critters.process(trim` 112 | 113 | 114 | $title 115 | 116 | 117 | 118 |

Hello World!

119 | 120 | 121 | `); 122 | 123 | expect(result).toMatch(''); 124 | expect(result).toMatch( 125 | `` 126 | ); 127 | expect(result).toMatchSnapshot(); 128 | }); 129 | 130 | test('should keep existing link tag attributes', async () => { 131 | const critters = new Critters({ 132 | reduceInlineStyles: false, 133 | path: '/' 134 | }); 135 | const assets = { 136 | '/style.css': trim` 137 | h1 { color: blue; } 138 | ` 139 | }; 140 | critters.readFile = (filename) => assets[filename]; 141 | const result = await critters.process(trim` 142 | 143 | 144 | $title 145 | 146 | 147 | 148 |

Hello World!

149 | 150 | 151 | `); 152 | 153 | expect(result).toMatch(''); 154 | expect(result).toMatch( 155 | `` 156 | ); 157 | expect(result).toMatchSnapshot(); 158 | }); 159 | 160 | test('Does not decode entities in HTML document', async () => { 161 | const critters = new Critters({ 162 | path: '/' 163 | }); 164 | critters.readFile = (filename) => assets[filename]; 165 | const result = await critters.process(trim` 166 | 167 | 168 | <h1>Hello World!</h1> 169 | 170 | 171 | `); 172 | expect(result).toMatch('<h1>Hello World!</h1>'); 173 | }); 174 | 175 | test('Prevent injection via media attr', async () => { 176 | const critters = new Critters({ 177 | reduceInlineStyles: false, 178 | path: path.join(__dirname, 'src'), 179 | preload: 'media' 180 | }); 181 | 182 | const html = fs.readFileSync( 183 | path.join(__dirname, 'src/media-validation.html'), 184 | 'utf8' 185 | ); 186 | 187 | const result = await critters.process(html); 188 | expect(result).toContain( 189 | '' 190 | ); 191 | expect(result).toMatchSnapshot(); 192 | }); 193 | 194 | test('Skip invalid path', async () => { 195 | const consoleSpy = jest.spyOn(console, 'warn'); 196 | 197 | const critters = new Critters({ 198 | reduceInlineStyles: false, 199 | path: path.join(__dirname, 'src') 200 | }); 201 | 202 | const html = fs.readFileSync( 203 | path.join(__dirname, 'src/subpath-validation.html'), 204 | 'utf8' 205 | ); 206 | 207 | const result = await critters.process(html); 208 | expect(consoleSpy).not.toHaveBeenCalledWith( 209 | expect.stringContaining('Unable to locate stylesheet') 210 | ); 211 | expect(result).toMatchSnapshot(); 212 | }); 213 | 214 | it('should not load stylesheets outside of the base path', async () => { 215 | const critters = new Critters({ path: '/var/www' }); 216 | jest.spyOn(critters, 'readFile'); 217 | await critters.process(` 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | `); 226 | expect(critters.readFile).toHaveBeenCalledWith('/var/www/file.css'); 227 | expect(critters.readFile).not.toHaveBeenCalledWith( 228 | '/company-secrets/secret.css' 229 | ); 230 | }); 231 | }); 232 | -------------------------------------------------------------------------------- /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 ')) { 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-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/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 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /packages/critters/README.md: -------------------------------------------------------------------------------- 1 | 2 | > [!CAUTION] 3 | > Ownership of Critters has moved to the Nuxt team, who will be maintaining the project going forward. If you'd like to keep using Critters, please switch to the actively-maintained fork at https://github.com/danielroe/beasties. This repo is now archived and won't receive any future updates. 4 | 5 |

6 | critters 7 |

Critters

8 |

9 | 10 | > Critters is a plugin that inlines your app's [critical CSS] and lazy-loads the rest. 11 | 12 | ## critters [![npm](https://img.shields.io/npm/v/critters.svg)](https://www.npmjs.org/package/critters) 13 | 14 | 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). 15 | 16 | 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. 17 | 18 | ## Features 19 | 20 | - Fast - no browser, few dependencies 21 | - Integrates with Webpack [critters-webpack-plugin] 22 | - Supports preloading and/or inlining critical fonts 23 | - Prunes unused CSS keyframes and media queries 24 | - Removes inlined CSS rules from lazy-loaded stylesheets 25 | 26 | ## Installation 27 | 28 | First, install Critters as a development dependency: 29 | 30 | ```sh 31 | npm i -D critters 32 | ``` 33 | 34 | or 35 | 36 | ```sh 37 | yarn add -D critters 38 | ``` 39 | 40 | ## Simple Example 41 | 42 | ```js 43 | import Critters from 'critters'; 44 | 45 | const critters = new Critters({ 46 | // optional configuration (see below) 47 | }); 48 | 49 | const html = ` 50 | 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 `