Opened 3 years ago
Last modified 2 weeks ago
#55639 new enhancement
Implement Async CSS
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | |
Component: | Script Loader | Keywords: | |
Focuses: | performance | Cc: |
Description
Initially created as a Performance Lab issue: https://github.com/WordPress/performance/issues/120 by @dainemawer. Copied description below:
Another pattern to possibly follow is Asynchronous CSS - this was suggested by the Filament Group at some point and has had some decent results: https://www.filamentgroup.com/lab/load-css-simpler/
It is slightly hacky, but it involves loading CSS files with media attribute set to print - this allows the browser to load the stylesheet in a non render block fashion. Using the onload attribute, we can set media back to all so that the stylesheet is applied as one would expect. As fallback, the original link is included in a a <noscript> tag incase JS borks out:
<link rel="stylesheet" href="/path/to/my.css" media="print" onload="this.media='all'" /> <noscript> <!-- No JS --> <link rel="stylesheet" href="/path/to/my.css" media="all" /> </noscript>
This could possibly be an extension of wp_enqueue_style by adding another parameter:
<?php wp_enqueue_style( $handle, $src, $deps, $ver, $media = 'all', $async = true ); ?>
What about just printing the stylesheet in the footer instead? This would avoid the need for JavaScript.
On my blog, for example, I have a Social Links block in my footer. Because of this, there's no need for the large block stylesheet (cf. gutenberg#69613 ) to be loaded in the
HEAD
and block rendering. So I'm moving it to the footer via:And this fixes the performance problem. Since it is printed at
wp_footer
, after which there is content to render (normally) and since the footer is far outside the initial viewport (normally) then there should be no FOUC.