How to remove an enqueued script in WordPress using wp_dequeue_script

The wp_dequeue_script function in WordPress is used to remove a previously enqueued script from the queue before it is outputted on the page. This can be useful when you want to prevent a certain script from being loaded, for example if it conflicts with other scripts or if it is not needed for a specific page or section of the website.

By using wp_dequeue_script, you can effectively control which scripts are loaded on your WordPress site, improving performance and preventing potential conflicts between scripts.

Parameters and Return Value of wp_dequeue_script function

  • $handle (string, required): Name of the script to be removed.

The wp_dequeue_script function does not return a value.

Examples

How to dequeue a script in WordPress

Use the wp_dequeue_script function to remove a script from the queue in WordPress.

if ( !is_admin() ) {
 wp_dequeue_script( 'jquery' );
}

This code snippet checks if the current page is not the admin page using the is_admin function. If it’s not the admin page, it dequeues the ‘jquery’ script using the wp_dequeue_script function.

How to conditionally dequeue a script in WordPress

Conditionally dequeue a script based on certain conditions using the wp_dequeue_script function.

function dequeue_custom_script() {
 if ( is_page( 'contact' ) ) {
 wp_dequeue_script( 'custom-script' );
 }
}
add_action( 'wp_enqueue_scripts', 'dequeue_custom_script' );

In this example, the dequeue_custom_script function is hooked into the wp_enqueue_scripts action. It checks if the current page is the ‘contact’ page using the is_page function, and if true, dequeues the ‘custom-script’ using the wp_dequeue_script function.

How to dequeue a script in a specific template in WordPress

Dequeue a script only in a specific template file in WordPress using the wp_dequeue_script function.

function dequeue_script_in_template() {
 if ( is_page_template( 'custom-template.php' ) ) {
 wp_dequeue_script( 'custom-script' );
 }
}
add_action( 'wp_enqueue_scripts', 'dequeue_script_in_template' );

This code snippet uses the dequeue_script_in_template function, which is hooked into the wp_enqueue_scripts action. It checks if the current page is using the ‘custom-template.php’ template file using the is_page_template function, and if true, dequeues the ‘custom-script’ using the wp_dequeue_script function.

Conclusion

In conclusion, the wp_dequeue_script function is a powerful tool for WordPress developers to remove unwanted scripts from their website. By using this function, developers can improve page load times, reduce unnecessary HTTP requests, and ensure that only the necessary scripts are loaded. This can lead to a better user experience and improved website performance. Understanding how to properly use wp_dequeue_script can greatly benefit WordPress developers in creating efficient and optimized websites.

Related WordPress Functions