Disable Javascript on Specific Page/Post

With this code you can disable (unnecessary) script or JS files (plugin) on specific page or post to reducing https request and can increase speed of your WordPress site before page or post loads.

HOW TO:
1. Open main .php and search wp_enqueue_script or script file name
2. Open your theme’s functions.php file
3. Copy, Paste and Edit code below and click Update File
EXAMPLE:
In this example, we’re disabling or loading Javascript file Contact Form 7 (‘contact-form-7‘) except in selected page or post (e.g. Contact)

add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
 
function my_deregister_javascript() {
   if ( !is_page('Contact') ) {
    wp_deregister_script( 'contact-form-7' );
     }
}

1. Disabling Javascript on Page

Edit Home or page and javascript-name-file according your JS files

add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
 
function my_deregister_javascript() {
   if ( !is_page('Home') ) {
    wp_deregister_script( 'javascript-name-file' );
     }
}

2. Disabling Javascript on Post

For post using post id (e.g. ‘1‘) and javascript-name-file according your JS files

add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );
 
function my_deregister_javascript() {
   if ( !is_single('1') ) {
    wp_deregister_script( 'javascript-name-file' );
     }
}

Once Updated File, the script will (deregister) no longer load except the page or post specify.

2 thoughts on “Disable Javascript on Specific Page/Post”

  1. For exercise, Try using contact-form-7 plugin and disable the Javascript for other page/post except the contact page only using this code:

    <code>
    add_action( ‘wp_print_scripts’, ‘my_dereg_javascript’, 100 );
    function my_dereg_javascript() {
    if ( !is_page( ‘contact’ ) ) {
    wp_deregister_script( ‘contact-form-7’ );
    }
    }
    </code>

    Contact Page >> “contact” not “Contact US” etc

  2. Your code is not working for me am getting Your PHP code changes were rolled back due to an error on line 859 of file wp-content/themes/frontier/functions.php. Please fix and try saving again.

    syntax error, unexpected token "if"

Give Us Feedback