Last active
February 11, 2023 20:50
-
-
Save aguilar1181/5f874bce4eb273221f39f734f8b83f43 to your computer and use it in GitHub Desktop.
add to WordPress themes functions.php to preload assets without a plugin
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
<?php | |
/** | |
* Preloading WordPress assets without a plugin. | |
* Change function name to something more unique. | |
* Priority is set to 0 to include as high in the <head> DOM as possible. Change priority if needed. | |
* Use WordPress is_page() to target specific page or is_front_page() to target ONLY homepage as in Option #1 | |
* If asset needs to be preloaded globally use Option #2. | |
* For multiple assets clone the link tag instead of the entire echo block. | |
* Change 'as' attribute accordingly. Values for 'as' can be found here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-as. | |
* Use abolute paths. For external assets paste the url, for internal assets use WordPress functions to construct URL. | |
*/ | |
add_action('wp_head', 'my_preloads', 0); | |
function my_preloads() { | |
// Option #1 | |
if ( is_front_page() ) { | |
echo ' | |
<link rel="preload" as="image" href="ABSOLUTE_PATH_TO_ASSET">'; | |
} | |
// Option #2 | |
echo ' | |
<link rel="preload" as="image" href="ABSOLUTE_PATH_TO_ASSET"> | |
<link rel="preload" as="font" href="ABSOLUTE_PATH_TO_ASSET"> | |
<link rel="preload" as="script" href="ABSOLUTE_PATH_TO_ASSET"> | |
'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment