• Stars
    star
    9,919
  • Rank 3,321 (Top 0.07 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extract & Inline Critical-path CSS in HTML pages

NPM version Build Status Coverage

critical

Critical extracts & inlines critical-path (above-the-fold) CSS from HTML

Preview

Install

npm i -D critical

Build plugins

Demo projects

Usage

Include:

import {generate} from 'critical';

Full blown example with available options:

generate({
  // Inline the generated critical-path CSS
  // - true generates HTML
  // - false generates CSS
  inline: true,

  // Your base directory
  base: 'dist/',

  // HTML source
  html: '<html>...</html>',

  // HTML source file
  src: 'index.html',

  // Your CSS Files (optional)
  css: ['dist/styles/main.css'],

  // Viewport width
  width: 1300,

  // Viewport height
  height: 900,

  // Output results to file
  target: {
    css: 'critical.css',
    html: 'index-critical.html',
    uncritical: 'uncritical.css',
  },

  // Extract inlined styles from referenced stylesheets
  extract: true,

  // ignore CSS rules
  ignore: {
    atrule: ['@font-face'],
    rule: [/some-regexp/],
    decl: (node, value) => /big-image\.png/.test(value),
  },
});

Generate and inline critical-path CSS

Basic usage:

generate({
  inline: true,
  base: 'test/',
  src: 'index.html',
  target: 'index-critical.html',
  width: 1300,
  height: 900,
});

Generate critical-path CSS

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} = await generate({
  base: 'test/',
  src: 'index.html',
  width: 1300,
  height: 900,
});

Generate critical-path CSS with multiple resolutions

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,
    },
  ],
});

Generate critical-path CSS and ignore specific selectors

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 critical-path CSS and specify asset rebase behaviour

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}`,
});

Options

Name Type Default Description
inline boolean|object false Inline critical-path CSS using filamentgroup's loadCSS. Pass an object to configure inline-critical
base string path.dirname(src) or process.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 the src option.
css array [] An array of paths to css files, file globs, Vinyl file objects or source CSS strings.
src string Location of the HTML source to be operated against
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
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 over width and height 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 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 for details. (https://github.com/pocketjoso/penthouse#usage-1).
ignore array or object undefined Ignore CSS rules. See postcss-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 for penthouse.
request object {} Configuration options for got.
cleanCSS object {level: { 1: { all: true }, 2: { all: false, removeDuplicateFontRules: true, removeDuplicateMediaBlocks: true, removeDuplicateRules: true, removeEmpty: true, mergeMedia: true } }} Configuration options for CleanCSS which let's you configure the optimization level for the generated critical css
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.

CLI

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

Gulp

import gulp from 'gulp';
import log from 'fancy-log';
import {stream as critical} from 'critical';

// Generate & Inline Critical-path CSS
gulp.task('critical', () => {
  return gulp
    .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'));
});

Why?

Why is critical-path CSS important?

CSS is required to construct the render tree for your pages and JavaScript will 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 CSS and the time to deliver it is as small as possible.

Why should critical-path CSS be inlined?

For best performance, you may want to consider inlining the critical CSS directly into the HTML document. This eliminates additional roundtrips in 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.

FAQ

Are there any sample projects available using Critical?

Why, yes!. Take a look at this Gulp project which demonstrates using Critical to generate and inline critical-path CSS. It also includes a mini-tutorial that walks through how to use it in a simple webapp.

When should I just use Penthouse directly?

The main differences between Critical and Penthouse, a module we use, 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 otherwise involved 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 into the DOM (sometimes common in Angular apps) I recommend using Penthouse directly. It will require you to supply styles upfront, but this may provide a higher level of accuracy if you find Critical isn't serving your needs.

What other alternatives to Critical are available?

FilamentGroup maintain a criticalCSS node module, which similar to Penthouse will find and output the critical-path CSS for your pages. The PageSpeed Optimization modules for nginx, apache, IIS, ATS, and Open Lightspeed can do all the heavy lifting automatically when you enable the prioritize_critical_css filter

Is Critical stable and suitable for production use?

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.

Can I contribute?

Of course. We appreciate all of our contributors and welcome contributions to improve the project further. If you're uncertain whether an addition should be made, feel free to open up an issue and we can discuss it.

Maintainers

This module is brought to you and maintained by the following people:

License

Apache-2.0 © Addy Osmani, Ben Zörb

More Repositories

1

backbone-fundamentals

📖 A creative-commons book on Backbone.js for beginners and advanced users alike
JavaScript
9,294
star
2

essential-js-design-patterns

Repo for my 'Learning JavaScript Design Patterns' book
HTML
4,254
star
3

es6-tools

An aggregation of tooling for using ES6 today
3,954
star
4

basket.js

A script and resource loader for caching & loading files with localStorage
JavaScript
3,362
star
5

es6-equivalents-in-es5

WIP - ES6 Equivalents In ES5
2,533
star
6

puppeteer-webperf

Automating Web Performance testing with Puppeteer 🎪
JavaScript
1,775
star
7

a11y

Accessibility audit tooling for the web (beta)
JavaScript
1,704
star
8

tmi

TMI (Too Many Images) - discover your image weight on the web
JavaScript
1,639
star
9

timing.js

Navigation Timing API measurement helpers
JavaScript
1,503
star
10

critical-path-css-tools

Tools to prioritize above-the-fold (critical-path) CSS
1,141
star
11

getUserMedia.js

Shim for getUserMedia(). Uses native implementation for modern browsers and a Flash fallback for everyone else.
JavaScript
908
star
12

critical-path-css-demo

Above-the-fold CSS generation + inlining using Critical & Gulp
ApacheConf
532
star
13

backbone-boilerplates

Backbone.js stack boilerplates demonstrating integration with Express, Ruby, PHP, Grails and more.
JavaScript
488
star
14

webpack-lighthouse-plugin

A Webpack plugin for Lighthouse
JavaScript
290
star
15

sublime-fixmyjs

SublimeText package for FixMyJS
Python
250
star
16

predictive-fetching

Improve performance by predictively fetching pages a user is likely to need
238
star
17

storage-on-the-web

🗃 Comparing storage options for the open web in 2016
225
star
18

visibly.js

A cross-browser Page Visibility API shim
JavaScript
221
star
19

learning-jsdp

Learning JavaScript Design Patterns: 2nd Edition - The Examples
HTML
212
star
20

sublime-build-systems

Sublime Text build systems
202
star
21

yeoman-examples

A repo of up to date examples using Yeoman
JavaScript
202
star
22

oust

Extract URLs to stylesheets, scripts, links, images or HTML imports from HTML
JavaScript
176
star
23

cssprettifier-bookmarklet

A bookmarklet for prettifying your CSS
JavaScript
174
star
24

polymer-boilerplate

A Polymer.js template for building fast, robust web apps using Web Components
JavaScript
166
star
25

pubsubz

Another Pub/Sub implementation
JavaScript
164
star
26

backbone-mobile-search

A Backbone.js + jQuery Mobile sample app using AMD for separation of modules, Require.js for dependency management + template externalisation and Underscore for templating
JavaScript
154
star
27

prism-js

A Polymer element for syntax highlighting with Prism.js
HTML
149
star
28

starter

A simple, git-clone friendly starting point for personal projects.
JavaScript
145
star
29

memoize.js

A faster JavaScript memoizer
JavaScript
143
star
30

largescale-demo

Scalable JS architecture demo for #jqcon
JavaScript
138
star
31

psi-gulp-sample

Sample Gulp project using PSI
JavaScript
126
star
32

preact-hn

🗞 Preact Hacker News
JavaScript
122
star
33

network-emulation-conditions

Network emulation / throttling conditions (2G, 3G, 4G, Wifi etc) ☎️
JavaScript
108
star
34

bubblesort

Bubble Sort implementation with O(n^2) complexity.
JavaScript
107
star
35

polymer-filters

Polymer filters for formatting values of expressions.
JavaScript
105
star
36

angular1-dribbble-pwa

Angular 1 Dribbble Progressive Web App demo
JavaScript
102
star
37

ember-progressive-webapp

Ember.js Zuperkulblog PWA (built with FastBoot and ember-cli)
JavaScript
97
star
38

memory-mysteries

V8 memory mysteries (sample app)
CSS
84
star
39

smaller-pictures-app

Smaller Pics Progressive Web App
JavaScript
82
star
40

x-instagram

[Deprecated] A Polymer element for querying the Instagram API (Note: not yet updated to Polymer 0.5.x)
JavaScript
76
star
41

x-imager

Responsive images using Imager.js and Polymer
74
star
42

backbonejs-gallery

A Backbone, Underscore and jQuery Templates based image gallery (early early beta)
JavaScript
72
star
43

todomvc-angular-4

Angular 4.x TodoMVC implementation
TypeScript
66
star
44

socketchat

SocketChat - a beginners chat app using SocketStream
CSS
63
star
45

github-watchers-button

An Embeddable GitHub 'Watchers' Button For External Pages
JavaScript
63
star
46

gulp-uncss-task

[Deprecated] Use gulp-uncss instead please.
JavaScript
63
star
47

yt-jukebox

A YouTube Jukebox element built with Polymer & Yeoman
JavaScript
61
star
48

critical-path-angular-demo

Above-the-fold CSS generation + inlining using Critical, Gulp & Angular
JavaScript
60
star
49

native-media-resizing

Draft proposal for browser-level media resizing
59
star
50

catclock

Polymer + Material Timer/Countdown/Countdown app (alpha)
JavaScript
56
star
51

recursive-binarysearch

Recursive Binary Search with O(log N) complexity
JavaScript
56
star
52

selectionsort

Selection sort with O(n^2) time complexity
JavaScript
56
star
53

polymer-grunt-example

Polymer + Grunt
JavaScript
56
star
54

microtemplatez

Another compact micro-templating solution
JavaScript
55
star
55

page-er

A Polymer element for paginating model data
CSS
53
star
56

google-slides

⚡ An offline-enabled Polymer slide-deck
HTML
53
star
57

flickly-wireframe

The jQuery mobile wireframe for Flickly
52
star
58

grunt-uncss-sass-example

An example of using grunt-uncss on a Sass project
JavaScript
52
star
59

sparkle-trail

<sparkle-trail> Polymer element - useful as a pre-loader
CSS
51
star
60

cssdiet

(WIP) - A DevTools extension for multi-page unused CSS auditing
JavaScript
46
star
61

a11y-webapp

A11y WebApp built with Polymer (WIP)
JavaScript
45
star
62

backbone-koans-qunit

Backbone Koans for QUnit
JavaScript
44
star
63

github-client

Angular GitHub client for Firefox OS
JavaScript
44
star
64

video-js

A Polymer element for Video.js
CSS
42
star
65

generator-webapp-uncss

Yeoman generator with grunt-uncss
JavaScript
42
star
66

lottie-animation-demo

Network-aware adaptive loading with Lottie Web
JavaScript
42
star
67

spine.bitly

(Demo app) A Spine.js Bit.ly client for shortening URLs and archiving references to these links offline.
JavaScript
39
star
68

backbone-aura

Backbone Aura
38
star
69

es2015-todomvc-chrome

ES2015 TodoMVC app that works without a transpiler
JavaScript
38
star
70

critical-css-weather-app

Critical-path CSS optimized weather app
JavaScript
37
star
71

polymer-blog

A tutorial app for generator-polymer
JavaScript
33
star
72

generator-boilerplate

A simple Yeoman generator using Git submodules to clone over a boilerplate hosted elsewhere on GitHub
JavaScript
31
star
73

npm-and-polymer-demo

Demo of Polymer + Paper elements working off npm3
HTML
31
star
74

jquery-roundrr

A jQuery plugin for plotting interactive content galleries in a circle form
JavaScript
30
star
75

polymer-localforage

A Polymer element for Mozilla's localForage (async storage via IndexedDB or WebSQL)
HTML
30
star
76

devtools-timeline-model-browser

Browser-friendly helper for parsing DevTools Timeline traces into structured profiling data models
JavaScript
29
star
77

mustache-for-chromeapps

A special build of mustache that works in Chrome Apps under CSP
JavaScript
28
star
78

addyosmani

GitHub README
27
star
79

tmdb-viewer-load-more

Accessibility-friendly version of TMDB Viewer (load-more)
JavaScript
25
star
80

active-route

Active view routing for Polymer extending <template>
CSS
25
star
81

webapp-scaffold

Polymer webapp scaffold element
CSS
25
star
82

typeahead-country

A Polymer element for autocompleting country names
24
star
83

react-interop

React + Polymer + X-Tag interop
JavaScript
24
star
84

vue-cli-todomvc

TodoMVC built using the Vue.js 2.0 CLI 🍰
JavaScript
22
star
85

polymer-browserify-vulcanize

Polymer + Browserify + Vulcanize
JavaScript
22
star
86

es6-starter

A minimal starting point for using ES6 today.
JavaScript
21
star
87

faster-video

A Polymer element for <video> with playback speed controls
JavaScript
21
star
88

js-shapelib

A minimalist JavaScript library for drawing objects around a Circle or Ellipse
JavaScript
19
star
89

element-query

Element queries with Polymer (experimental fork)
CSS
19
star
90

clientside-sample-buildfile

A Client-side ANT Build File Example
19
star
91

parsely

A small utility for parsing URLs of all types.
JavaScript
18
star
92

video-player

A themeable Polymer video element
JavaScript
16
star
93

page-router

Declarative URL routing for Polymer elements.
CSS
16
star
94

polymer-eventemitter

A Polymer event emitter element with support for wildcards, many and once.
JavaScript
15
star
95

lighthouse-reports

Quick module for getting Lighthouse reports in JSON form
JavaScript
15
star
96

generator-es6

An ES6.now project generator for Yeoman.
JavaScript
14
star
97

aura

A scalable, event-driven JavaScript architecture for developing widget-based applications. Works with Backbone.js and other frameworks.
14
star
98

jquery-googleviewer-plugin

A compact Google Viewer plugin
14
star
99

medium-backups

HTML
13
star
100

css3-transition-fallbacks

CSS3 Transition Fallback demos
13
star