Solving "Preload key requests" point on PageSpeed for WordPress sites

Getting a good score on Google PageSpeed is important if you want to rank higher and in the process provide a better experience to your users. However with the constantly updating system of PageSpeed you have to tackle new issues. One of the recent updates now focuses on preloading key requests on your site.


Update 3rd Jan 2020 : Modified the code to support extra attributes like crossorin and type that is required for some other types of content such as Fonts file. 

Browsers are smart and to make use of it there's something called pre-loading of requests, that is you tell the browser to already pre-load a set of resources ahead of time which you know will be used in the future.

This tutorial is focused towards WordPress sites but the technique is same for any site, it's just a few lines of HTML that goes on top of the <head> of your website.

I won't discuss what's preloading a request is in detail but if you would like to know more check this out: https://web.dev/uses-rel-preload/

Note: There is another point that sounds very similar, it is "preconnect", it is for pre-fetching DNS that we know will be required.  There will be another similar tutorial for that, so stay tuned.

It looks something like this in the PageSpeed report:



/*
* Preload the s**t out of Google
*/

function stramaxon_preload_requests_html() {
    $preloadRequests = array(
        array(
            'as'   => 'style',
            'href' => '/wp-content/themes/example/style.css',
            'type' => 'text/css'
        ),
        array(
            'as'   => 'script',
            'href' => '/wp-content/themes/example/main.js',
            'type' => 'text/javascript'
        ),
        array(
            'as'   => 'font',
            'href' => '/wp-content/themes/example/font.woff2',
            'type' => 'font/woff2',
            'crossorigin' => 'crossorigin'
        )
    );

    $linksHtml = '';

    foreach ($preloadRequests as $val) {

    	$attrs = '';

    	foreach ($val as $key => $att ) {
    		$attrs .= $key . '="' . $att . '" ';
    	}

        $linksHtml .= '<link '. $attrs .' rel="preload">';
    }
 
    echo $linksHtml;
}

add_action('wp_head', 'stramaxon_preload_requests_html', -100);

The above code will go into your theme's functions.php file. All you have to do here it add elements to the array  $preloadRequests and define the href and as value as required.

Are you looking to solve another Google PageSpeed x WordPress problem? Let us know in the comments, we will be happy to write a blog post for that as well.