wp enqueue script – wp_enqueue . Preload key requests using

I think you want to add this as a resource hint to the HTML, not as a server push header. as preload not supported by wp native wp_resource_hints function, you will need to create a custom function to print preload tag and append somewhere at the beginning of the head section of 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 purpose of the above code is to show a concept, a possible way to tackle your needs. You will need to adapt to your needs and it would be a good idea to abstract it and make it reusable and more generic.

Some other important points:

  • You should exercise caution and avoid using preload only for a select few and really important and necessary resources
  • At the time of this writing support for preload is around 90% according to caniuse.com
  • This directive is still a recommendation draft. Therefore, supported media types and attributes may change in the future. Please check the latest W3C recommendation before use.

Leave a Comment