I’ve been working with Sage 10 for a while and am looking to optimize the performance of my theme by implementing critical CSS. I’m aware of the importance of inlining the “above-the-fold” CSS to speed up the initial paint of the webpage. However, with the build processes and tools integrated into Sage 10 (especially with @roots/bud), I’m not entirely sure about the best approach.
Specifically:
How do I best integrate a tool/package like @roots/bud-criticalcss into the Sage 10 build process?
Once the critical CSS is generated, how do I inline it effectively in my Blade templates?
How do I ensure that the rest of my styles (those not considered “critical”) are loaded asynchronously without causing any flicker or delay in rendering?
Are there any specific gotchas or recommendations when implementing this in a Sage 10 theme with Bedrock?
If anyone has experience with this or can point me towards a comprehensive guide or tutorial, I’d greatly appreciate it!
How do I best integrate a tool/package like @roots/bud-criticalcss into the Sage 10 build process?bud-criticalcss has worked fine for me, despite being experimental. Conditionally enabling it based on isProduction as per the example is the way to go. You’ll find emitted styles in ./public/css/critical/<module>.<hash>.css. To make it more portable, I’ve set the src to process.env.WP_HOME, but that may not be appropriate for you. bud-criticalcss doesn’t appear to support multiple sources and multiple critical css outputs, so if you need multiple entries, may may need to come up with another approach.
Once the critical CSS is generated, how do I inline it effectively in my Blade templates? AFAIK, this is a developer decision. I would use $asset->contents() to leverage Acorn to deal with your asset manifest and grab the contents. Then hook into <head> and output the <style> tags.
How do I ensure that the rest of my styles (those not considered “critical”) are loaded asynchronously without causing any flicker or delay in rendering? This is a large question, and very dependent on your project. The link from Harry Roberts below touches on this.
Are there any specific gotchas or recommendations when implementing this in a Sage 10 theme with Bedrock? Only one springs to mind: Try to utilise Bud as much as possible. Having build steps outside of Bud can generate friction with your workflow. If bud-criticalcss doesn’t hit the spot, reach for a Webpack plugin over some external CLI tool. Having everything driven from Bud makes builds fast and reliable, and you’ll thank yourself if you choose to go down the CI/CD path.