Mark Thomas Miller

Plugin development: conditional script loading

While developing Altair, I ran into a slight issue: its scripts and stylesheets were being loaded on every page of my website, rather than only single posts. Users shouldn’t need to download these files unless they’re on a page where Altair is running, so it needed to be fixed.

If you’re having the same problem as I was, here’s a clean solution: wrap your plugin’s styles and scripts in an if statement, then use wp_enqueue_scripts to make its containing function run when you want files to be loaded. For instance, here’s an example that only adds styles/scripts when the user is viewing a standalone post:

function zeph_conditional_load() {
    if (is_single()) {
        wp_enqueue_style('zeph-style');
        wp_enqueue_script('zeph-script');
    }
add_action('wp_enqueue_scripts', 'zeph_conditional_load');

Note to beginners: you can replace zeph with the name of your plugin. You’ll also need to provide parameters so the code can actually locate your scripts. For more information on this, you should read WordPress’ developer resources!

Basically, if (is_single()) checks if the user loaded a single post. If the user loaded something other than a post, is_single() will return false and the style and script will not be loaded.

You can check for other things, and combinations of things, too, like to see if a plugin option is enabled and if the user loaded a post:

function zeph_conditional_load() {
    $options = get_option('zeph_settings');
    if (isset($options['zeph_powerswitch']) && is_single()) {
        wp_enqueue_style('zeph-style');
        wp_enqueue_script('zeph-script');
    }
}
add_action('wp_enqueue_scripts', 'zeph_conditional_load');

…and so on. The next time you’re at the bar, make sure you tell the story of when you saved all of those server resources! Your fellow bar patrons will surely love it.