{"id":13426742,"url":"https://github.com/addyosmani/critical","last_synced_at":"2025-05-13T11:05:35.799Z","repository":{"id":18183841,"uuid":"21299916","full_name":"addyosmani/critical","owner":"addyosmani","description":"Extract \u0026 Inline Critical-path CSS in HTML pages","archived":false,"fork":false,"pushed_at":"2025-01-31T07:22:15.000Z","size":5632,"stargazers_count":10129,"open_issues_count":45,"forks_count":377,"subscribers_count":138,"default_branch":"master","last_synced_at":"2025-05-13T11:05:22.278Z","etag":null,"topics":["critical-css","critical-path-css","critical-path-styles","css","inline-css","inline-styles"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"square/retrofit","license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/addyosmani.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"license","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-06-28T09:31:42.000Z","updated_at":"2025-05-13T10:20:00.000Z","dependencies_parsed_at":"2024-01-12T03:04:06.042Z","dependency_job_id":"772ebf5a-e2cc-4fdf-99c5-96f4209bc5d7","html_url":"https://github.com/addyosmani/critical","commit_stats":{"total_commits":655,"total_committers":39,"mean_commits":"16.794871794871796","dds":0.3893129770992366,"last_synced_commit":"b326606aa9b207f6ebc43d6c6c43b3a6b14d62fd"},"previous_names":[],"tags_count":111,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/addyosmani%2Fcritical","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/addyosmani%2Fcritical/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/addyosmani%2Fcritical/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/addyosmani%2Fcritical/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/addyosmani","download_url":"https://codeload.github.com/addyosmani/critical/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253929362,"owners_count":21985802,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["critical-css","critical-path-css","critical-path-styles","css","inline-css","inline-styles"],"created_at":"2024-07-31T00:01:43.273Z","updated_at":"2025-05-13T11:05:35.732Z","avatar_url":"https://github.com/addyosmani.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","CSS","Head","css","\\*nix/\\*nux","性能优化","Miscellaneous","Frameworks/Libraries","Frontend","Frameworks / Resources","Node modules","🔧 Utilities \u0026 Miscellaneous"],"sub_categories":["References","HTML tags","Tags HTML","HTML etiketleri","Developer","redux 扩展","macros","Meetups","Web Components","Tools","C"],"readme":"[![NPM version][npm-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coverage][coveralls-image]][coveralls-url]\n\n# critical\n\nCritical extracts \u0026 inlines critical-path (above-the-fold) CSS from HTML\n\n\u003cimg src=\"https://raw.githubusercontent.com/addyosmani/critical/master/preview.png\" alt=\"Preview\" width=\"378\"\u003e\n\n## Install\n\n```sh\nnpm i -D critical\n```\n\n## Build plugins\n\n- [grunt-critical](https://github.com/bezoerb/grunt-critical)\n- Gulp users should use Critical directly\n- For Webpack use [html-critical-webpack-plugin](https://github.com/anthonygore/html-critical-webpack-plugin)\n\n## Demo projects\n\n- [Optimize a basic page with Gulp](https://github.com/addyosmani/critical-path-css-demo) with a [tutorial](https://github.com/addyosmani/critical-path-css-demo#tutorial)\n- [Optimize an Angular boilerplate with Gulp](https://github.com/addyosmani/critical-path-angular-demo)\n- [Optimize a Weather app with Gulp](https://github.com/addyosmani/critical-css-weather-app)\n\n## Usage\n\nInclude:\n\n```js\nimport {generate} from 'critical';\n```\n\nFull blown example with available options:\n\n```js\ngenerate({\n  // Inline the generated critical-path CSS\n  // - true generates HTML\n  // - false generates CSS\n  inline: true,\n\n  // Your base directory\n  base: 'dist/',\n\n  // HTML source\n  html: '\u003chtml\u003e...\u003c/html\u003e',\n\n  // HTML source file\n  src: 'index.html',\n\n  // Your CSS Files (optional)\n  css: ['dist/styles/main.css'],\n\n  // Viewport width\n  width: 1300,\n\n  // Viewport height\n  height: 900,\n\n  // Output results to file\n  target: {\n    css: 'critical.css',\n    html: 'index-critical.html',\n    uncritical: 'uncritical.css',\n  },\n\n  // Extract inlined styles from referenced stylesheets\n  extract: true,\n\n  // ignore CSS rules\n  ignore: {\n    atrule: ['@font-face'],\n    rule: [/some-regexp/],\n    decl: (node, value) =\u003e /big-image\\.png/.test(value),\n  },\n});\n```\n\n### Generate and inline critical-path CSS\n\nBasic usage:\n\n```js\ngenerate({\n  inline: true,\n  base: 'test/',\n  src: 'index.html',\n  target: 'index-critical.html',\n  width: 1300,\n  height: 900,\n});\n```\n\n### Generate critical-path CSS\n\nBasic usage:\n\n```js\ngenerate({\n  base: 'test/',\n  src: 'index.html',\n  target: 'styles/main.css',\n  width: 1300,\n  height: 900,\n});\n```\n\nGenerate and minify critical-path CSS:\n\n```js\ngenerate({\n  base: 'test/',\n  src: 'index.html',\n  target: 'styles/styles.min.css',\n  width: 1300,\n  height: 900,\n});\n```\n\nGenerate, minify and inline critical-path CSS:\n\n```js\ngenerate({\n  inline: true,\n  base: 'test/',\n  src: 'index.html',\n  target: {\n    html: 'index-critical.html',\n    css: 'critical.css',\n  },\n  width: 1300,\n  height: 900,\n});\n```\n\nGenerate and return output via callback:\n\n```js\ngenerate({\n    base: 'test/',\n    src: 'index.html',\n    width: 1300,\n    height: 900,\n    inline: true\n}, (err, {css, html, uncritical}) =\u003e {\n    // You now have critical-path CSS as well as the modified HTML.\n    // Works with and without target specified.\n    ...\n});\n```\n\nGenerate and return output via promise:\n\n```js\ngenerate({\n    base: 'test/',\n    src: 'index.html',\n    width: 1300,\n    height: 900\n}).then((({css, html, uncritical})) =\u003e {\n    // You now have critical-path CSS as well as the modified HTML.\n    // Works with and without target specified.\n    ...\n}).error(err =\u003e {\n    ...\n});\n```\n\nGenerate and return output via async function:\n\n```js\nconst {css, html, uncritical} = await generate({\n  base: 'test/',\n  src: 'index.html',\n  width: 1300,\n  height: 900,\n});\n```\n\n### Generate critical-path CSS with multiple resolutions\n\nWhen your site is adaptive and you want to deliver critical CSS for multiple screen resolutions this is a useful option.\n_note:_ (your final output will be minified as to eliminate duplicate rule inclusion)\n\n```js\ngenerate({\n  base: 'test/',\n  src: 'index.html',\n  target: {\n    css: 'styles/main.css',\n  },\n  dimensions: [\n    {\n      height: 200,\n      width: 500,\n    },\n    {\n      height: 900,\n      width: 1200,\n    },\n  ],\n});\n```\n\n### Generate critical-path CSS and ignore specific selectors\n\nThis is a useful option when you e.g. want to defer loading of webfonts or background images.\n\n```js\ngenerate({\n  base: 'test/',\n  src: 'index.html',\n  target: {\n    css: 'styles/main.css',\n  },\n  ignore: {\n    atrule: ['@font-face'],\n    decl: (node, value) =\u003e /url\\(/.test(value),\n  },\n});\n```\n\n### Generate critical-path CSS and specify asset rebase behaviour\n\n```js\ngenerate({\n  base: 'test/',\n  src: 'index.html',\n  target: {\n    css: 'styles/main.css',\n  },\n  rebase: {\n    from: '/styles/main.css',\n    to: '/folder/subfolder/index.html',\n  },\n});\n```\n\n```js\ngenerate({\n  base: 'test/',\n  src: 'index.html',\n  target: {\n    css: 'styles/main.css',\n  },\n  rebase: (asset) =\u003e `https://my-cdn.com${asset.absolutePath}`,\n});\n```\n\n### Options\n\n| Name                | Type                   | Default                                                                                                                                                                                | Description                                                                                                                                                                                                                                                                                                                                                                     |\n| ------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| inline              | `boolean`\\|`object`    | `false`                                                                                                                                                                                | Inline critical-path CSS using filamentgroup's loadCSS. Pass an object to configure [`inline-critical`](https://github.com/bezoerb/inline-critical#inlinehtml-styles-options)                                                                                                                                                                                                   |\n| base                | `string`               | `path.dirname(src)` or `process.cwd()`                                                                                                                                                 | Base directory in which the source and destination are to be written                                                                                                                                                                                                                                                                                                            |\n| html                | `string`               |                                                                                                                                                                                        | HTML source to be operated against. This option takes precedence over the `src` option.                                                                                                                                                                                                                                                                                         |\n| css                 | `array`                | `[]`                                                                                                                                                                                   | An array of paths to css files, file globs, [Vinyl](https://www.npmjs.com/package/vinyl) file objects or source CSS strings.                                                                                                                                                                                                                                                                        |\n| src                 | `string`               |                                                                                                                                                                                        | Location of the HTML source to be operated against                                                                                                                                                                                                                                                                                                                              |\n| target              | `string` or `object`   |                                                                                                                                                                                        | Location of where to save the output of an operation. Use an object with 'html' and 'css' props if you want to store both                                                                                                                                                                                                                                                       |\n| width               | `integer`              | `1300`                                                                                                                                                                                 | Width of the target viewport                                                                                                                                                                                                                                                                                                                                                    |\n| height              | `integer`              | `900`                                                                                                                                                                                  | Height of the target viewport                                                                                                                                                                                                                                                                                                                                                   |\n| dimensions          | `array`                | `[]`                                                                                                                                                                                   | An array of objects containing height and width. Takes precedence over `width` and `height` if set                                                                                                                                                                                                                                                                              |\n| extract             | `boolean`              | `false`                                                                                                                                                                                | Remove the inlined styles from any stylesheets referenced in the HTML. It generates new references based on extracted content so it's safe to use for multiple HTML files referencing the same stylesheet. Use with caution. Removing the critical CSS per page results in a unique async loaded CSS file for every page. Meaning you can't rely on cache across multiple pages |\n| inlineImages        | `boolean`              | `false`                                                                                                                                                                                | Inline images                                                                                                                                                                                                                                                                                                                                                                   |\n| assetPaths          | `array`                | `[]`                                                                                                                                                                                   | List of directories/urls where the inliner should start looking for assets                                                                                                                                                                                                                                                                                                      |\n| maxImageFileSize    | `integer`              | `10240`                                                                                                                                                                                | Sets a max file size (in bytes) for base64 inlined images                                                                                                                                                                                                                                                                                                                       |\n| rebase              | `object` or `function` | `undefined`                                                                                                                                                                            | Critical tries it's best to rebase the asset paths relative to the document. If this doesn't work as expected you can always use this option to control the rebase paths. See [`postcss-url`](https://github.com/postcss/postcss-url) for details. (https://github.com/pocketjoso/penthouse#usage-1).                                                                           |\n| ignore              | `array` or `object`    | `undefined`                                                                                                                                                                            | Ignore CSS rules. See [`postcss-discard`](https://github.com/bezoerb/postcss-discard) for usage examples. If you pass an array all rules will be applied to atrules, rules and declarations;                                                                                                                                                                                    |\n| ignoreInlinedStyles | `boolean`              | `false`                                                                                                                                                                                | Ignore inlined stylesheets                                                                                                                                                                                                                                                                                                                                                      |\n| userAgent           | `string`               | `''`                                                                                                                                                                                   | User agent to use when fetching a remote src                                                                                                                                                                                                                                                                                                                                    |\n| penthouse           | `object`               | `{}`                                                                                                                                                                                   | Configuration options for [`penthouse`](https://github.com/pocketjoso/penthouse).                                                                                                                                                                                                                                                                                               |\n| request             | `object`               | `{}`                                                                                                                                                                                   | Configuration options for [`got`](https://github.com/sindresorhus/got).                                                                                                                                                                                                                                                                                                         |\n| cleanCSS            | `object`               | `{level: {  1: { all: true }, 2: { all: false, removeDuplicateFontRules: true, removeDuplicateMediaBlocks: true, removeDuplicateRules: true, removeEmpty: true, mergeMedia: true } }}` | Configuration options for [`CleanCSS`](https://github.com/clean-css/clean-css) which let's you configure the optimization level for the generated critical css                                                                                                                                                                                                                  |\n| user                | `string`               | `undefined`                                                                                                                                                                            | RFC2617 basic authorization: user                                                                                                                                                                                                                                                                                                                                               |\n| pass                | `string`               | `undefined`                                                                                                                                                                            | RFC2617 basic authorization: pass                                                                                                                                                                                                                                                                                                                                               |\n| strict              | `boolean`              | `false`                                                                                                                                                                                | Throw an error on css parsing errors or if no css is found.                                                                                                                                                                                                                                                                                                                     |\n\n## CLI\n\n```sh\nnpm install -g critical\n```\n\ncritical works well with standard input.\n\n```sh\ncat test/fixture/index.html | critical --base test/fixture --inline \u003e index.critical.html\n```\n\nOr on Windows:\n\n```bat\ntype test\\fixture\\index.html | critical --base test/fixture --inline \u003e index.critical.html\n```\n\nYou can also pass in the critical CSS file as an option.\n\n```sh\ncritical test/fixture/index.html --base test/fixture \u003e critical.css\n```\n\n## Gulp\n\n```js\nimport gulp from 'gulp';\nimport log from 'fancy-log';\nimport {stream as critical} from 'critical';\n\n// Generate \u0026 Inline Critical-path CSS\ngulp.task('critical', () =\u003e {\n  return gulp\n    .src('dist/*.html')\n    .pipe(\n      critical({\n        base: 'dist/',\n        inline: true,\n        css: ['dist/styles/components.css', 'dist/styles/main.css'],\n      })\n    )\n    .on('error', (err) =\u003e {\n      log.error(err.message);\n    })\n    .pipe(gulp.dest('dist'));\n});\n```\n\n## Why?\n\n### Why is critical-path CSS important?\n\n\u003e CSS is required to construct the render tree for your pages and JavaScript\n\u003e will often block on CSS during initial construction of the page.\n\u003e You should ensure that any non-essential CSS is marked as non-critical\n\u003e (e.g. print and other media queries), and that the amount of critical CSS\n\u003e and the time to deliver it is as small as possible.\n\n### Why should critical-path CSS be inlined?\n\n\u003e For best performance, you may want to consider inlining the critical CSS\n\u003e directly into the HTML document. This eliminates additional roundtrips\n\u003e in the critical path and if done correctly can be used to deliver a\n\u003e “one roundtrip” critical path length where only the HTML is a blocking resource.\n\n## FAQ\n\n### Are there any sample projects available using Critical?\n\nWhy, yes!. Take a look at [this](https://github.com/addyosmani/critical-path-css-demo) Gulp project\nwhich demonstrates using Critical to generate and inline critical-path CSS. It also includes a mini-tutorial\nthat walks through how to use it in a simple webapp.\n\n### When should I just use Penthouse directly?\n\nThe main differences between Critical and [Penthouse](https://github.com/pocketjoso/penthouse), a module we\nuse, are:\n\n- Critical will automatically extract stylesheets from your HTML from which to generate critical-path CSS from,\n  whilst other modules generally require you to specify this upfront.\n- Critical provides methods for inlining critical-path CSS (a common logical next-step once your CSS is generated)\n- Since we tackle both generation and inlining, we're able to abstract away some of the ugly boilerplate otherwise\n  involved in tackling these problems separately.\n\nThat said, if your site or app has a large number of styles or styles which are being dynamically injected into\nthe DOM (sometimes common in Angular apps) I recommend using Penthouse directly. It will require you to supply\nstyles upfront, but this may provide a higher level of accuracy if you find Critical isn't serving your needs.\n\n### What other alternatives to Critical are available?\n\nFilamentGroup maintain a [criticalCSS](https://github.com/filamentgroup/criticalCSS) node module, which\nsimilar to [Penthouse](https://github.com/pocketjoso/penthouse) will find and output the critical-path CSS for\nyour pages. The PageSpeed Optimization modules for nginx, apache, IIS, ATS, and Open Lightspeed can do all the heavy\nlifting automatically when you enable the [prioritize_critical_css](https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery) filter\n\n### Is Critical stable and suitable for production use?\n\nCritical has been used on a number of production sites that have found it stable for everyday use.\nThat said, we welcome you to try it out on your project and report bugs if you find them.\n\n## Can I contribute?\n\nOf course. We appreciate all of our [contributors](https://github.com/addyosmani/critical/graphs/contributors) and\nwelcome contributions to improve the project further. If you're uncertain whether an addition should be made, feel\nfree to open up an issue and we can discuss it.\n\n## Maintainers\n\nThis module is brought to you and maintained by the following people:\n\n- Addy Osmani - Creator ([Github](https://github.com/addyosmani) / [Twitter](https://twitter.com/addyosmani))\n- Ben Zörb - Primary maintainer ([Github](https://github.com/bezoerb) / [Twitter](https://twitter.com/bezoerb))\n\n## License\n\n[Apache-2.0 © Addy Osmani, Ben Zörb](license)\n\n[npm-url]: https://www.npmjs.com/package/critical\n[npm-image]: https://img.shields.io/npm/v/critical.svg\n[ci-url]: https://github.com/addyosmani/critical/actions?workflow=Tests\n[ci-image]: https://github.com/addyosmani/critical/workflows/Tests/badge.svg\n[coveralls-url]: https://coveralls.io/github/addyosmani/critical?branch=master\n[coveralls-image]: https://img.shields.io/coveralls/github/addyosmani/critical/master.svg\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faddyosmani%2Fcritical","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faddyosmani%2Fcritical","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faddyosmani%2Fcritical/lists"}