Created
December 30, 2020 17:31
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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