- Notifications
You must be signed in to change notification settings - Fork0
Extract & Inline Critical-path CSS in HTML pages
License
Charllie-one/critical
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Critical extracts & inlines critical-path (above-the-fold) CSS from HTML
npm i -D critical
- grunt-critical
- Gulp users should use Critical directly
- For Webpack usehtml-critical-webpack-plugin
- Optimize a basic page with Gulp with atutorial
- Optimize an Angular boilerplate with Gulp
- Optimize a Weather app with Gulp
Include:
import{generate}from'critical';
Full blown example with available options:
generate({// Inline the generated critical-path CSS// - true generates HTML// - false generates CSSinline:true,// Your base directorybase:'dist/',// HTML sourcehtml:'<html>...</html>',// HTML source filesrc:'index.html',// Your CSS Files (optional)css:['dist/styles/main.css'],// Viewport widthwidth:1300,// Viewport heightheight:900,// Output results to filetarget:{css:'critical.css',html:'index-critical.html',uncritical:'uncritical.css',},// Extract inlined styles from referenced stylesheetsextract:true,// ignore CSS rulesignore:{atrule:['@font-face'],rule:[/some-regexp/],decl:(node,value)=>/big-image\.png/.test(value),},});
Basic usage:
generate({inline:true,base:'test/',src:'index.html',target:'index-critical.html',width:1300,height:900,});
Basic usage:
generate({base:'test/',src:'index.html',target:'styles/main.css',width:1300,height:900,});
Generate and minify critical-path CSS:
generate({base:'test/',src:'index.html',target:'styles/styles.min.css',width:1300,height:900,});
Generate, minify and inline critical-path CSS:
generate({inline:true,base:'test/',src:'index.html',target:{html:'index-critical.html',css:'critical.css',},width:1300,height:900,});
Generate and return output via callback:
generate({base:'test/',src:'index.html',width:1300,height:900,inline:true},(err,{css, html, uncritical})=>{// You now have critical-path CSS as well as the modified HTML.// Works with and without target specified. ...});
Generate and return output via promise:
generate({base:'test/',src:'index.html',width:1300,height:900}).then((({css, html, uncritical}))=>{// You now have critical-path CSS as well as the modified HTML.// Works with and without target specified. ...}).error(err=>{ ...});
Generate and return output via async function:
const{css, html, uncritical}=awaitgenerate({base:'test/',src:'index.html',width:1300,height:900,});
When your site is adaptive and you want to deliver critical CSS for multiple screen resolutions this is a useful option.note: (your final output will be minified as to eliminate duplicate rule inclusion)
generate({base:'test/',src:'index.html',target:{css:'styles/main.css',},dimensions:[{height:200,width:500,},{height:900,width:1200,},],});
This is a useful option when you e.g. want to defer loading of webfonts or background images.
generate({base:'test/',src:'index.html',target:{css:'styles/main.css',},ignore:{atrule:['@font-face'],decl:(node,value)=>/url\(/.test(value),},});
generate({base:'test/',src:'index.html',target:{css:'styles/main.css',},rebase:{from:'/styles/main.css',to:'/folder/subfolder/index.html',},});
generate({base:'test/',src:'index.html',target:{css:'styles/main.css',},rebase:(asset)=>`https://my-cdn.com${asset.absolutePath}`,});
Name | Type | Default | Description |
---|---|---|---|
inline | boolean |object | false | Inline critical-path CSS using filamentgroup's loadCSS. Pass an object to configureinline-critical |
base | string | path.dirname(src) orprocess.cwd() | Base directory in which the source and destination are to be written |
html | string | HTML source to be operated against. This option takes precedence over thesrc option. | |
css | array | [] | An array of paths to css files, file globs orVinyl file objects. |
src | string | Location of the HTML source to be operated against | |
target | string orobject | Location of where to save the output of an operation. Use an object with 'html' and 'css' props if you want to store both | |
width | integer | 1300 | Width of the target viewport |
height | integer | 900 | Height of the target viewport |
dimensions | array | [] | An array of objects containing height and width. Takes precedence overwidth andheight if set |
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 |
inlineImages | boolean | false | Inline images |
assetPaths | array | [] | List of directories/urls where the inliner should start looking for assets |
maxImageFileSize | integer | 10240 | Sets a max file size (in bytes) for base64 inlined images |
rebase | object orfunction | 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. Seepostcss-url for details. (https://github.com/pocketjoso/penthouse#usage-1). |
ignore | array orobject | undefined | Ignore CSS rules. Seepostcss-discard for usage examples. If you pass an array all rules will be applied to atrules, rules and declarations; |
ignoreInlinedStyles | boolean | false | Ignore inlined stylesheets |
userAgent | string | '' | User agent to use when fetching a remote src |
penthouse | object | {} | Configuration options forpenthouse . |
request | object | {} | Configuration options forgot . |
user | string | undefined | RFC2617 basic authorization: user |
pass | string | undefined | RFC2617 basic authorization: pass |
strict | boolean | false | Throw an error on css parsing errors or if no css is found. |
npm install -g critical
critical works well with standard input.
cat test/fixture/index.html| critical --base test/fixture --inline> index.critical.html
Or on Windows:
type test\fixture\index.html| critical --base test/fixture --inline> index.critical.html
You can also pass in the critical CSS file as an option.
critical test/fixture/index.html --base test/fixture> critical.css
importgulpfrom'gulp';importlogfrom'fancy-log';import{streamascritical}from'critical';// Generate & Inline Critical-path CSSgulp.task('critical',()=>{returngulp.src('dist/*.html').pipe(critical({base:'dist/',inline:true,css:['dist/styles/components.css','dist/styles/main.css'],})).on('error',(err)=>{log.error(err.message);}).pipe(gulp.dest('dist'));});
CSS is required to construct the render tree for your pages and JavaScriptwill often block on CSS during initial construction of the page.You should ensure that any non-essential CSS is marked as non-critical(e.g. print and other media queries), and that the amount of critical CSSand the time to deliver it is as small as possible.
For best performance, you may want to consider inlining the critical CSSdirectly into the HTML document. This eliminates additional roundtripsin the critical path and if done correctly can be used to deliver a“one roundtrip” critical path length where only the HTML is a blocking resource.
Why, yes!. Take a look atthis Gulp projectwhich demonstrates using Critical to generate and inline critical-path CSS. It also includes a mini-tutorialthat walks through how to use it in a simple webapp.
The main differences between Critical andPenthouse, a module weuse, are:
- Critical will automatically extract stylesheets from your HTML from which to generate critical-path CSS from,whilst other modules generally require you to specify this upfront.
- Critical provides methods for inlining critical-path CSS (a common logical next-step once your CSS is generated)
- Since we tackle both generation and inlining, we're able to abstract away some of the ugly boilerplate otherwiseinvolved in tackling these problems separately.
That said, if your site or app has a large number of styles or styles which are being dynamically injected intothe DOM (sometimes common in Angular apps) I recommend using Penthouse directly. It will require you to supplystyles upfront, but this may provide a higher level of accuracy if you find Critical isn't serving your needs.
FilamentGroup maintain acriticalCSS node module, whichsimilar toPenthouse will find and output the critical-path CSS foryour pages. The PageSpeed Optimization modules for nginx, apache, IIS, ATS, and Open Lightspeed can do all the heavylifting automatically when you enable theprioritize_critical_css filter
Critical has been used on a number of production sites that have found it stable for everyday use.That said, we welcome you to try it out on your project and report bugs if you find them.
Of course. We appreciate all of ourcontributors andwelcome contributions to improve the project further. If you're uncertain whether an addition should be made, feelfree to open up an issue and we can discuss it.
This module is brought to you and maintained by the following people:
About
Extract & Inline Critical-path CSS in HTML pages
Resources
License
Stars
Watchers
Forks
Packages0
Languages
- JavaScript67.1%
- HTML32.6%
- CSS0.3%