How to preload key requests on WordPress

Last updated on March 31, 2022 | By

To preload key requests from WordPress for Pagespeed, you can either use a free plugin, with code on funtions.php or use Wp Rocket (paid plugin).

What are Key Requests and how to check yours

Key requests are critical resources for the page render. By preloading, you are telling the browser to fetch the resource early with the rel=preload tag.

<link rel="preload" as="script" href="critical.js">

To check if you need to preload key requests, go to Pagespeed Insights, do a page test, and go to “Preload key requests”.

preload key request
/main.css needs to preload

How to preload WordPress key requests

To preload fonts or files only when needed, add the following code on functions.php or download the Insert Headers and Footers by WPBeginner plugin to add the code.

Create a preload tag and paste the file URL’s from Pagespeed. Replace the with your file URL from Pagespeed on the href below. It will be something like this for a CSS file that needs to preload on the homepage:

// preload css only on homepage
function wpb_hook_javascript() {
	if (current_user_can( 'update_core' )) {
            return;
        } else {
            // Check for the page you want to target
    if ( is_front_page() ) {
    ?>
        <link rel="preload" href="you_critical_asset.css" as="style">
    <?php
}
}
}
add_action('wp_head', 'wpb_hook_javascript', 99);
⚠️ Be careful placing code on functions.php or in the Insert Head and Footer plugin, it can brick your website. Always backup your site before any changes.

How the code looks on functions.php or in the Insert Head and Footer plugin:

image 2

Every time you need a file to preload, change the is_front_page to is_page, and add something that identifies the page:

// When Page 42 (ID) is being displayed.
is_page( 42 );
 
// When the Page with a post_title of "Contact" is being displayed.
is_page( 'Contact' );
 
// When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( 'about-me' );

Code will look something like this for preloading a CSS file on the page /about:

// preload css only on page about
function wpb_hook_javascript() {
	if (current_user_can( 'update_core' )) {
            return;
        } else {
            // Check for the page you want to target
    if ( is_page('about') ) {
    ?>
        <link rel="preload" href="style.css" as="style">
    <?php
}
}
}
add_action('wp_head', 'wpb_hook_javascript', 99);

How to preload wordpress fonts key requests with Wp Rocket

Insert the desired local font on the “Preload” tab on Wp Rocket:

preload key request wp rocket

This method will preload the files even on pages where it’s not needed.

Get your Core Web Vitals optimized

Leave a Comment