What is Critical Css

First screen Key CSS

When rendering a page, browser resolution will render the page only after the part of the CSS style has been loaded and parsed. This rendering method means that if the CSS file is large, the user will have to wait a long time to see the rendering result. To solve this problem, we proposed an unconventional rendering path, often referred to as the Critical rendering path, to improve the rendering speed of a page. The optimization we need to do is to find the minimum set of Critical CSS for rendering the first screen and write them to the section so that the browser can render the page as soon as it receives the HTML file. The rest of the CSS can be loaded asynchronously.

Summary: Critical Css is the minimum set of Css for rendering the first screen.

Access to critical CSS via the CriticalCSS website

Vue-cli client extract Critical CSS

Extract the CSS

Vue – cli4, for example

css.extract

introduce

  • Type: boolean | Object
  • Default: The value is true in the production environment and false in the development environment

Whether to extract the CSS from the component into a separate CSS file (instead of dynamically injecting inline code into JavaScript).

It is also always disabled when building Web Components (the style is inline and injected into shadowRoot).

When building as a library, you can also set it to false to prevent users from importing CSS themselves.

Extracting CSS is disabled by default in development mode because it is incompatible with CSS hot overloading. However, you can still explicitly set this value to true to force extraction in all cases.

  • The development environment

extractfalse, the style is embedded toheadIn the.

  • The production environment

Extract to true, style split, outer chain to head.

Form two CSS files:

App. [contetHash]. CSS: The CSS extracted from the Vue component

Chunk-vendors.[contentHash]. CSS: The CSS that third-party libraries depend on

Inside the plugin

  • Mini-css-extract-plugin: Extract CSS into a separate file, create a CSS file for each JS file containing CSS, and support on-demand loading of CSS and SourceMaps
  • @intervolga/optimize-cssnano-plugin: optimize and compress CSS

insufficient

Either the styles are all embedded in the head and the HTML file is too large, or the page is too white for too long if there is a network problem.

In view of this deficiency, we take a look at thevueHow to extract the first screen rendering CSS in the client projectcritical css.

Extract critical CSS

Use the webpack plugin critical-CSS-webpack-plugin

critical-css-webpack-plugin

Project configuration

Vue – cli4. X as an example

Install
npm install critical-css-webpack-plugin -D
Copy the code
vue.config.js
const criticalCssWebpackPlugin = require('critical-css-webpack-plugin')

/ critical css Options
const criticalCssOptions = {
    // type: Boolean /object, whether to inline generated critical-path CSS. //true: Generate HTML,false: generates CSS, object: passes configuration objects to 'inline-critical' inline:true, / /type: string, read and write source directory base: resolve('dist'), / /type: string, the HTML source to operate on, which takes precedence over the SRC option // HTML:' ', / /type: array, CSS array of paths // CSS: [], //type: string, the location of the HTML source to manipulate SRC:'index.html', / /typeIf you want to store both 'HTML' and 'CSS', use the object target of 'HTML' and 'CSS' :'index.html', / /type: integerWidth: 1300, //type: integerHeight: 900, //type: array, an array of widths and heights, if set, takes precedence over the width and height options (dimensions: [], //)type: Boolean, whether to compress generated critical-path CSS minify:true, / /type: Boolean, used with caution, removes inline styles from HTML. It generates a new reference based on the extracted content, so it is safe to reference the same style file in multiple HTML files. Removing the key CSS for each page generates a unique asynchronously loaded CSS for each page. Means you can't cache multiple pages extract:false, / /type: Boolean, inline image inlineImages:true, / /typeAssetPaths: [], // Sets the maximum size (in bytes) of base64 inline images maxImageFileSize: 10240000, //type: object/function, Critical tries relative document assets path rebase: undefined, //type: array
    ignore: [],
    // type: string, obtain the userAgent when remote SRC // userAgent:' ', / /typePenthouse: {// propertiesToRemove: ['background'], // selector forceInclude: ['.card'.'.card__list'.'.card__main'.'.card__img'.'.card__article'],
        forceExclude: []
    },
    // type: object, global offset configuration options Request: {}, //type: string, RFC2617 Authorization: user user: undefined, //type: string, RFC2617 Authorization: pass Pass: undefined, //type: Boolean, if CSS cannot be found, throw strict:false
};

module.exports = {
    chainWebpack: config => {
        config.plugin('critical')
                .use(criticalCssWebpackPlugin,
                    [
                        criticalCssOptions
                    ]
                ).tap(error => {
                    console.log(error, 'critical css generate error');
                    return error
                })
    }
}
Copy the code

After the configuration is complete, run the commandnpm run buildBuild, viewdist/index.htmlAnd you can see the extractedcritical cssInserted into theheadThe remainingcssStill extrinsic chain form is introduced.

suchindex.htmlThe files will not be large, and the simple page style can be displayed when the network is unstable.

critical-css-webpack-pluginThe core of plug-ins iscritical.criticalThe core usepenthouseAnd then we’ll elaboratecriticalandpenthouse.

Critical plug-in

Introduction to the Critical plug-in, using the core component library penthouse.

Extract critical CSS from HTML and inline critical-path into HTML

Install
npm i -D critical
Copy the code
Usage

Configuration file critical.js:

const critical = require('critical');
critical.generate({
  // Inline the generated critical-path CSS
  // - true generates HTML
  // - false generates CSS
  inline: true. });Copy the code

Run the critical.js configuration file in node

node critical.js
Copy the code
Critical Options

From www.npmjs.com/package/cri…

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 or Vinyl file objects.
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
minify boolean true Enable minification of generated critical-path CSS
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. (Github.com/pocketjoso/…).
ignore array object undefined
userAgent string ‘ ‘ User agent to use when fetching a remote src
penthouse object {} Configuration options for penthouse.
request object {} Configuration options for got.
user string undefined RFC2617 basic authorization: user
pass string undefined RFC2617 basic authorization: pass
strict boolean false Throw an error if no css is found
Global Install And Cli
npm install -g critical
Copy the code
critical test/fixture/index.html --base test/fixture > critical.css
Copy the code

penthouse

Penthouse is introduced

Critical path CSS generator

Install
npm i -D penthouse
Copy the code
Usage
penthouse({
  url: 'http://google.com',
  cssString: 'body { color: red }'. }).then(criticalCss => {
  // use the critical css
  fs.writeFileSync('outfile.css', criticalCss);
})
Copy the code
Options

Corresponding to PenthouseOptions in the Critical plug-in

Name Type Default Description
url string Accessible url. Use file:/// protocol for local html files.
cssString string Original css to extract critical css from
css string Path to original css file on disk (if using instead of cssString)
width integer 1300 Width for critical viewport
height integer 900 Height for critical viewport
screenshots object Configuration for screenshots (not used by default). See Screenshot example
keepLargerMediaQueries boolean false Keep media queries even for width/height values larger than critical viewport.
forceInclude array [] Array of css selectors to keep in critical css, even if not appearing in critical viewport. Strings or regex (f.e. [‘.keepMeEvenIfNotSeenInDom’, /^.button/])
forceExclude array [] Array of css selectors to remove in critical css, even if appearing in critical viewport. Strings or regex (f.e. [‘.doNotKeepMeEvenIfNotSeenInDom’, /^.button/])
propertiesToRemove array [‘ (.)transition(.)’, ‘cursor’, ‘pointer-events’, ‘(-webkit-)? tap-highlight-color’, ‘(.*)user-select’] ] Css properties to filter out from critical css
timeout integer 30000 Ms; abort critical CSS generation after this time
puppeteer object Settings for puppeteer. See Custom puppeteer browser example
pageLoadSkipTimeout integer 0 Ms; stop waiting for page load after this time (for sites when page load event is unreliable)
renderWaitTime integer 100 ms; wait time after page load before critical css extraction starts (also before “before” screenshot is taken, if used)
blockJSRequests boolean true set to false to load JS (not recommended)
maxEmbeddedBase64Length integer 1000 characters; strip out inline base64 encoded resources larger than this
maxElementsToCheckPerSelector integer undefined Can be specified to limit nr of elements to inspect per css selector, reducing execution time.
userAgent string ‘Penthouse Critical Path CSS Generator’ specify which user agent string when loading the page
customPageHeaders object et extra http headers to be sent with the request for the url.
cookies array [] For formatting of each cookie, see Puppeteer setCookie docs
strict boolean false Make Penthouse throw on errors parsing the original CSS. Legacy option, not recommended.
allowedResponseCode number|regex|function Let Penthouse stop if the server response code is not matching this value. number and regex types are tested against the response.status(). A function is also allowed and gets Response as argument. The function should return a boolean.

SSR server extract Critical CSS

introduce

Introduction to the

The recommended way to manage CSS when SSR server rendering is simply to use *. Vue within a single file component

  • Parallel to HTML, the component is scoped CSS
  • Can use pre-processor or PostCSS
  • Hot-reload during development

More importantly, vue-style-loader (the loader used internally by vue-Loader) has some special features for server-side rendering:

  • Generic programming experience on both client and server sides.

  • When bundleRenderer is used, critical CSS is automatically injected.

  • If used during server-side rendering, the component’s CSS can be collected and inlined in HTML (handled automatically when using the Template option). On the client side, when the component is used for the first time, vue-style-loader checks if the component already has a SERVER-inlined CSS – if not, CSS is dynamically injected via the

The demo sample

Pages /index.vue Renders the top page

<template>
    <div class="index"> </div> </template> <style>. } </style>Copy the code

Create pages/test.vue page to verify whether SSR will automatically inject critical CSS

<template>
    <div class="test"> Test </div> </template> <style>test {
    color: red;
}
</style>
Copy the code
  1. inindex.vueThe introduction oftest.vueAfter the service is started,test.vueStyle alsostyleThe form is embedded in the page
  2. Not inindex.vueThe introduction oftest.vueAfter the service is started,test.vueStyles are not embedded in the first render page

Summary: SSR server will automatically inject the first screen rendering key CSS, no need to introduce other plug-ins.

Extract the CSS

The following uses nuxT framework configuration as an example: nuxt.config.js

SSR can extractCSS to an independent file through extractCSS, convenient cache.

export default {
    build: {
        extractCSS: true,}}Copy the code

conclusion

  • Both the client and server can passextractextractcssTo a separate file, external chain form is introduced
  • Clients can only be embeddedcsstoheadIn, or extracted into separate file external chain introduced, not extractedcritical css, need to add additional Webpack plugin to extract
  • Automatic server injectioncritical css, there is no need to introduce additional plug-ins

Reference documentation

  • This section describes the SSR server
  • Introduction to SSR NUXT framework
  • Vue CLI CSS configuration
  • critical
  • penthouse
  • inline-critical