How to Dequeue Scripts and Styles in WordPress for Improved Page Speed

Many WordPress plugins load scripts and styles on every page of a website even though they may just be needed on a few specific pages. For example, WooCommerce loads at least 3 scripts and 4 styles on every page, even if ecommerce functionality (like a cart or products) aren’t shown on those pages.

I recently went on a performance rampage at Universal Yums and removed ~300kb of enqueued assets that were not needed on our home page- which shows there can be quite a bit of fat to trim.

To find our which scripts and styles are enqueued, you’ll need to do a some detective work. First, install the Query Monitor plugin. This will let you know which scripts and styles are enqueued for a specific page.

Screenshot of site with Query Monitor running

Query monitor will show you all the scripts enqueued by WordPress for a specific page. It will also show you the “handle”, which is needed to dequeue the asset.

To dequeue scripts you can use the wp_print_scripts hook.

 * Remove scripts that have been enqueued by other plugins.
function prefix_remove_scripts() {
	if ( is_front_page() ) {
		wp_dequeue_script( 'woocommerce' );
		wp_dequeue_script( 'wc-add-to-cart' );
		wp_dequeue_script( 'wc-cart-fragments' );
		wp_dequeue_script( 'storefront-header-cart' );
add_action( 'wp_print_scripts', 'prefix_remove_scripts', 100 );

To dequeue styles you can use the wp_enqueue_scripts hook:

 * Remove styles that have been enqueued by other plugins.
function prefix_remove_styles() {
	if ( is_front_page() ) {
		wp_dequeue_style( 'wp-block-library' );
		wp_dequeue_style( 'wc-block-vendors-style' );
		wp_dequeue_style( 'wc-block-style' );
		wp_dequeue_style( 'woocommerce-inline' );
add_action( 'wp_enqueue_scripts', 'prefix_remove_styles', 100 );

I’ve limited the dequeues to the front page of the site in these code blocks, but you can use different page conditionals to remove the scripts and styles from where they are not needed.

You can include this code directly in the functions.php file of your theme, but I generally load a separate file as a class either from a mu-plugin or the theme. Here’s what that type of file might look like.

Leave a Reply