Skip to content

Instantly share code, notes, and snippets.

@celsobessa
Created December 30, 2020 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsobessa/7affa365dbe86a4ee85bdc358b748209 to your computer and use it in GitHub Desktop.
Save celsobessa/7affa365dbe86a4ee85bdc358b748209 to your computer and use it in GitHub Desktop.
Writes preload resource hints to HTML element generated by wp_head function on WordPress.
// 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/
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment