Automattic / twenty-nineteen-amp-prototype

2 stars 2 forks source link

Break up style.css into multiple CSS files that are enqueued as required just-in-time by components #6

Open westonruter opened 5 years ago

westonruter commented 5 years ago

In WP Rig the comments.php template includes this line:

wp_rig()->print_styles( 'wp-rig-comments' );

(Note that this print_styles() method is just a wrapper around wp_print_styles().)

This has the effect of adding a <link rel=stylesheet ...> for the theme's comments.css tag inline right before the div#comments element.

By splitting comments.css out of a single style.css there are a couple key benefits:

  1. The comments CSS is only included if the comments.php template is actually used, that is, if the CSS is actually needed. This is particularly helpful for AMP because there is less overall CSS that needs to be tree-shaken, which reduces processing time and also reduces the overall amount of CSS: the tree shaker is not able to eliminate all unused rules, and the best best way to reduce CSS is to not include it in the first place.
  2. The comments styling is not critical CSS as it is not needed until the user scrolls down to the bottom of the page. So requesting the stylesheet later reduces the amount of CSS being served in the critical rendering path. As a bonus, stylesheets loaded in the body are asynchronous and do not block rendering. This is less relevant for AMP since the plugin concatenates all CSS into the single style[amp-custom] element anyway, but adopting this practice is good for non-AMP pages and pages processed by the AMP plugin (for the point above).

The CSS for the theme is already broken up into separate SASS files. So it seems like it could be a minor effort to discontinue compiling _comments.scss into style.css and to rather compile it into a separate comments.css.

In the same way as the comments template, imagine of there were similar stylesheets for specific blocks or widgets (e.g. in Jetpack) which would only be printed when a given block or widget is actually used on the page.

For more on this, see WordPress 5.0 and Gutenberg: A better way to handle CSS overload.

danieldudzic commented 5 years ago

Thanks @westonruter,

This looks really interesting. Will definitely investigate and see if this is something we can implement :)