Preload key requests using wp_enqueue

I am presuming you want to add this as resource hints on the HTML and not as an server push header. As preload is not supported by WP native wp_resource_hints function, you would need to create a custom function printing the preload tags and add somewhere in the beginning of head section of the HTML. Something like the following.

// Adds preload resource hint to wp_head hook
add_action( 'wp_head', 'add_preload_resource_hint', -1);

/**
 * Writes preload resource hints.
 * 
 * Writes preload resource hints.
 */

function add_preload_resource_hint() {
    $template_directory = get_template_directory_uri();

    // preloading a stylesheet
    echo "<link rel=\"preload\" href=\"{$template_directory}/css/mystyles.css\" as=\"style\">";

    // preloading a script.
    echo "<link rel=\"preload\" href=\"{$template_directory}/js/myscript.js\" as=\"script\">";

    // preloading a font
    echo "<link rel=\"preload\" href=\"{$template_directory}/fonts/myfont.woff2\" as=\"font\">";

    // preloading an image.
    echo "<link rel=\"preload\" href=\"{$template_directory}/images/myimage.jpg\" as=\"font\">";

    // preloading a video.
    echo "<link rel=\"preload\" href=\"{$template_directory}/video/myvideo.m4v\" as=\"media\">";
    
    // preloading page 2 of a multi-page post
    echo "<link rel=\"preload\" href=\"/page/2/" as=\"document\">";

    // if preloading from another domain, it will probably be have CORS rules 
    // and you should use the crossorigin attribute
    echo "<link rel=\"preload\" href=\"{$template_directory}/fonts/myfont.woff2\" as=\"font\" crossorigin>";

    // for all types of content and attributes value
    // please check the latest W3C recommendation at
    // https://www.w3.org/TR/preload/


};

Important: the code above is intended to show a concept, aa possible way to deal with your needs. You will need to adapt to your needs and would be a good idea to abstract it and make reusable and more generalist.

A few other important points:

  • You should exercise caution and avoid using preload only for a few selected and really important and required resources
  • support for preload at the time of this writing is around 90% according to caniuse.com
  • this directive is still a recommendation draft. Therefore, the supported media types and attributes might change in the future. Check the latest W3C recommendation before using it.

Leave a Comment