DEV Community

Giulia Chiola
Giulia Chiola

Posted on • Originally published at giuliachiola.dev

Force include classes in critical CSS

Critical CSS build by Addy Osmani is a useful library that extracts and inlines critical-path CSS in HTML pages.

In the documentation page, there are a lot of configurations available but they are not the only ones! 😏

Critical CSS uses as its engine penthouse which has in turn a lot of configuration options. One of them, is forceInclude.

forceInclude: [...] description from docs 📚:

Array of css selectors to keep in critical css, even if not appearing in critical viewport. Strings or regex (f.e. ['.keepMeEvenIfNotSeenInDom', /^.button/])

For instance, if we want to add a cta class injected via JS and not available in DOM nodes when the critical path is generated, we have to configure our critical CSS options like this:

critical.generate({
  base: './',
  src: 'template-homepage.html',
  css: ['production/css/style-1.css' , 'production/css/style-2.css'],
  ....
  penthouse: {
    forceInclude: ['OPTIONAL-CLASS-HERE'],
  },
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)