Wordpress Plugin - Remove JS & CSS Bloat

How to remove JS & CSS bloat that is loaded on every page?

Gonzales is a WordPress plugin that can disable unneeded scripts on a page-level basis.

One notorious example would be plugin: Contact Form 7

Official document: Loading JavaScript and Stylesheet Only When it is Necessary The best: cf7unloaded/cf7unloaded.php at master · strategio/cf7unloaded

Remove Contact Form 7 scripts and styles through the WordPress action hook API

Conditionally Loading Scripts and Styles for WordPress Plugins

By looking at source code, has_shortcode() functions seems quite slow, so I will use more simpler approach.

function wpdocs_shortcode_scripts() {
    global $post;
    if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wpdocs-shortcode') ) {
        wp_enqueue_script( 'wpdocs-script');
    }
}

add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts', 999);


--

$page_id = get_queried_object_id();
$page_object = get_page( $page_id );
if ( strpos($page_object->post_content, '[/slider]') 

--

  JS: wp_register_script( 'jquery-form'
  JS: wp_enqueue_script( 'contact-form-7'
  CSS: wp_enqueue_style( 'contact-form-7'
  CSS: wp_enqueue_style( 'contact-form-7-rtl'

do_action( 'wpcf7_enqueue_scripts' ); 
do_action( 'wpcf7_enqueue_styles' );   

--

add_action( 'wpcf7_enqueue_styles', function() { wp_deregister_style( 'contact-form-7' ); } );
add_action( 'wpcf7_enqueue_scripts', function() { wp_deregister_script( 'jquery-form' ); } );

--

@see: http://contactform7.com/loading-javascript-and-stylesheet-only-when-it-is-necessary/

add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );

    if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
        wpcf7_enqueue_scripts();
    }
 
    if ( function_exists( 'wpcf7_enqueue_styles' ) ) {
        wpcf7_enqueue_styles();
    }

date 01. Jan 0001 | modified 28. May 2021
filename: Wordpress Plugin - Remove JS & CSS Bloat
Article Content