I’m currently doing some speed optimisation and one of the main things scoring the site down is:-
“Preload key requests 2.64 s
Consider using to prioritize fetching resources that are currently requested later in page load. Learn more.”
I enqueue all my styles and JS files in my functions.php as follows:-
wp_register_script('jquery-ui', get_template_directory_uri() . '/assets/js/jquery-ui.min.js', array(), '1.12.1');
wp_enqueue_script('jquery-ui');
wp_register_style( 'jquery-ui-css', get_template_directory_uri() . '/assets/css/jquery-ui.min.css', array(), '1.12.1');
wp_enqueue_style( 'jquery-ui-css' );
How would I go about using rel="preload"
with some of these files?
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.