Introduction

One of the larger issues with WordPress, in my opinion, is the amount of bloat that it delivers from page to page. This happens because WordPress software is distributed as Plugins and Themes that tend to ship with a larger functionality than each user may require. Additionally, WordPress enqueues scripts without prejudice on most pages, even where they aren’t required. An example of this is the plugin Contact Form 7. This is a very popular contact form plugin and when installed, the Javascript and CSS for this plugin will load globally, when they are only really required when a contact form is on the current page.

View all enqueued scripts and styles

Here’s a function to display all of the enqueued scripts on a given page:

/**
 * Used to var_dump all currently enqueued JS & CSS scripts.
 */
function var_dump_enqueued_scripts_and_styles(): void
{
    $enqueued_scripts = wp_scripts()->queue;
    $enqueued_styles = wp_styles()->queue;
    $enqueued_scripts_and_styles = array(
        'scripts' => $enqueued_scripts,
        'styles' => $enqueued_styles,
    );
    var_dump($enqueued_scripts_and_styles);
}
add_action( 'wp_enqueue_scripts', 'var_dump_enqueued_scripts_and_styles' );
add_action( 'wp_print_styles', 'var_dump_enqueued_scripts_and_styles' );

When placed in a loaded PHP file, such as the functions.php file within your child theme, this function will dump 2 arrays on the top of the page that lists out all of the loaded Javascript and CSS scripts.

Dequeue scripts for specific pages

If you see a script that you know is not required on every page, you can then use the following function to dequeue the script on all but the pages of your choice:

/**
 * Dequeues CF7 scripts unless page is the contact page, set by ID
 */
function load_cf7_on_contact_page(): void
{
    if( !is_page(1234) )
    {
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
    }
}
add_action( 'wp_enqueue_scripts', 'load_cf7_on_contact_page');

The function in this exact configuration will dequeue Contact Form 7 on all pages except from the page with the ID ‘1234’. However, you can use a page’s name, or ID to define a single page to leave the script queued on. If you wanted, you could modify this to use the WordPress function ‘get_post_type()‘ to only queue the script on posts of a given type, such as pages/posts.