Preload Header for Your Theme Stylesheet
Sends an HTTP Link preload header for your theme's main stylesheet, so browsers, and CDNs that support Early Hints, start downloading the CSS before the HTML has even arrived.
Opens WPIDE on
Code
// Extra files to preload: URL => 'style', 'script' or 'font'.
$wpide_link_preloads = array();
add_action( 'send_headers', function () use ( $wpide_link_preloads ) {
if ( headers_sent() || is_admin() ) {
return;
}
$theme = wp_get_theme();
$files = array( add_query_arg( 'ver', $theme->get( 'Version' ), get_stylesheet_uri() ) => 'style' ) + $wpide_link_preloads;
$values = array();
foreach ( $files as $url => $as ) {
$value = sprintf( '<%s>; rel=preload; as=%s', esc_url_raw( $url ), $as );
if ( 'font' === $as ) {
$value .= '; crossorigin';
}
$values[] = $value;
}
header( 'Link: ' . implode( ', ', $values ), false );
} );
Notes
Add more files (for example a key web font) to $wpide_link_preloads; keep the list short, since preloading too much slows everything else down.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.