Critical CSS plugin


#1

I’m looking to use webpack-plugin-critical in the webpack.config.optimize.js file, but I have no idea what settings would be needed as the example gives index.html as the src and dest, but as its WordPress its not a single page application.

Does anyone have any experience with using this (or other working packages) with WordPress and would you be able to share a working example?

Thanks!


#2

What about using pagespeed for nginx?
https://www.modpagespeed.com/doc/filter-prioritize-critical-css

And for static:


#3

You’re overthinking it imo. Just import/compile all of your critical CSS to something like critical.css and inline it with something like:

namespace App;

/**
 * Inject critical assets
 */
add_action('wp_head', function () {
    $critical = @realpath(asset_path('styles/critical.css'));
    if (file_exists($critical)) {
        echo '<style>'.@file_get_contents($critical).'</style>';
    }
}, 10);

#4

Thanks for this. Is there a webpack package you would you use to generate the critical.css file? I used to use penthouse with gulp but I don’t have much experience with webpack.


#5

I’m sure there’s something out there but depending on the project size I’d probably just resort to @importing all of the above the fold / scaffolding CSS into critical.css. I have no suggestions past that though as I haven’t had to do much more. :frowning:


#6

So I’ve managed to make some progress using critical-webpack-plugin. I’ve added the following to the webpack.config.optimize.js file to get it to generate a critical css file and then use the above code example to inject critical assets. (Replacing path/to/site with the url to your site).

const CriticalWebpackPlugin = require('critical-webpack-plugin');
module.exports = {
plugins: [
new ImageMinPlugin(...),
new CriticalWebpackPlugin({
      src: 'http://path/to/site',
      dest: 'critical.css',
      width: 480,
      height: 800,
      pathPrefix: '/styles',
      minify: true
    }),
]
} 

#7

In production sage appends cache busting string to file names so this path wouldn’t work. Is there a way to load file with that cache string name?


#8

@jasonbaciulis: For production builds a list of plain file names and
their production equivalents with hash can be found in
dist/assets.json:

{
  "scripts/customizer.js": "scripts/customizer_9ecd05b4.js",
  "styles/main.css": "styles/main_9ecd05b4.css",
  "scripts/main.js": "scripts/main_9ecd05b4.js"
}

#9

Whoops. Yes, asset_path().

I updated my code above.


#10

It works now but only without if (file_exists($critical)) statement. file_exists() check doesn’t work for me in another place in the theme as well.
Do you have an idea why it wouldn’t work even if a file does exist?

Also, I am not using @realpath like in your code, just an asset_path. Is this your own directive? Could you post the code for it?

Thanks.