One of the first things we learn when becoming a WordPress developer is how to load scripts and styles using the wp_enqueue_scripts
hook.
We can take this one step further and, instead of loading these assets on every page, we can conditionally load them only on the pages that need them. This means less things to load per page, less bandwidth and better site performance.
We do this using conditional tags.
WordPress conditional tags
WordPress gives you a ton of conditional tags that allow you to check the context of a page. And when used with wp_enqueue_script
and wp_enqueue_style
they all can be used to conditionally load your scripts and styles.
Some examples
This is especially useful if you are using any large libraries (like GSAP) but only on certain pages. Here is an example of how you can use the is_front_page() conditional tag to load scripts only on the front page:
function load_scripts_on_front_page()
{
if (is_front_page()) {
wp_enqueue_script('frontpage-script', 'path/to/my/script.js', array(), '1.0', true);
wp_enqueue_script('gsap', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js', array(), '1.0', true);
}
}
add_action('wp_enqueue_scripts', 'load_scripts_on_front_page');
In this example, we are using the is_front_page()
conditional tag to check if the user is on the front page and then using the wp_enqueue_script
function to enqueue a script called ‘frontpage-script’ and GSAP if the user is on the front page. This prevents these scripts from loading on other pages when it’s not needed.
Similarly, another conditional tag you can use is the is_page() conditional tag to load a script only on a specific page:
function load_script_on_about_page()
{
if (is_page('about')) {
wp_enqueue_script('aboutpage-script', 'path/to/my/script.js', array(), '1.0', true);
}
}
add_action('wp_enqueue_scripts', 'load_script_on_about_page');
Conclusion
By using WordPress conditional tags and the wp_enqueue_scripts
hook, you can ensure that your scripts and styles are loaded only when they are needed.
This can improve the performance of your website and provide a better user experience for your users. Less to load means a faster site.