Defer JavaScript and optimize CSS loading in WordPress
Render-blocking JavaScript and CSS are one of the most frequent reasons for poor Lighthouse scores. A normal <script src> in the <head> stops HTML parsing until the file is downloaded and executed. The defer attribute lets the browser download the script in the background and run it after the HTML is parsed. Deferred scripts still run in document order, so dependencies are kept.
Problem: Theme and plugin scripts block HTML parsing and delay the first render (First Contentful Paint), and the Google Fonts stylesheet adds extra connections before the text appears.
Solution: Add defer to selected script handles with the script_loader_tag filter, and open the connections to the font origins early with preconnect hints.
defer for selected scripts
<?php
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
$defer = array( 'my-theme-main', 'slick-slider' );
if ( in_array( $handle, $defer, true ) && false === strpos( $tag, ' defer' ) ) {
$tag = str_replace( ' src=', ' defer src=', $tag );
}
return $tag;
}, 10, 2 );
Choose the handles carefully:
- a script that has inline code depending on it (
wp_add_inline_script()after it, or code in the template) must not be deferred, otherwise the inline code runs first and fails; - if a deferred script depends on jQuery, jQuery can stay normal: it still loads first;
- do not defer jQuery itself while other plugins print inline
jQuery( ... )code.
The handles are visible in the id of the tags (id="my-theme-main-js") or with print_r( array_keys( wp_scripts()->registered ) );.
Preconnect for Google Fonts
Google Fonts needs two origins: the CSS from fonts.googleapis.com and the font files from fonts.gstatic.com. Opening these connections early saves the DNS and TLS time:
<?php
add_filter( 'wp_resource_hints', function ( $hints, $relation_type ) {
if ( 'preconnect' === $relation_type ) {
$hints[] = array( 'href' => 'https://fonts.googleapis.com' );
$hints[] = array( 'href' => 'https://fonts.gstatic.com', 'crossorigin' => 'anonymous' );
}
return $hints;
}, 10, 2 );
Also add &display=swap to the Google Fonts URL, so the text is shown with a system font while the web font loads. The fastest option is to host the fonts yourself: the .woff2 files in the theme and @font-face in its CSS, no third-party connections at all.
Check
In Lighthouse, the “Eliminate render-blocking resources” item lists what still blocks the render; the Performance tab of DevTools shows when each script runs.
Update (August 2023): Since WordPress 6.3, wp_enqueue_script() can do this itself: pass array( 'strategy' => 'defer', 'in_footer' => false ) as the last argument instead of true. WordPress then also takes care of the dependencies and inline scripts, so the filter above is only needed for scripts of plugins you cannot change.