CF7 CSS still loading even when form is not present (filters added)
-
Hi,
I’m trying to improve my site’s performance and avoid loading unnecessary assets from Contact Form 7 when no forms are present on the page.
I’ve added the following code to disable the default CSS and JS globally:
add_action( 'plugins_loaded', function() {
add_filter( 'wpcf7_load_js', '__return_false' );
add_filter( 'wpcf7_load_css', '__return_false' );
}, 1 );Then I conditionally load them only when a form is detected:
function lz_tiene_cf7_shortcode() {
global $post;
if ( ! is_a($post, 'WP_Post') ) return false;
if ( has_shortcode( $post->post_content, 'contact-form-7' ) ) return true;
if ( function_exists('has_block') && has_block('contact-form-7/contact-form-selector', $post ) ) return true;
return false;
}
function lz_cargar_cf7_condicional() {
if ( lz_tiene_cf7_shortcode() ) {
if ( function_exists( 'wpcf7_enqueue_scripts' ) ) wpcf7_enqueue_scripts();
if ( function_exists( 'wpcf7_enqueue_styles' ) ) wpcf7_enqueue_styles();
}
}
add_action( 'wp_enqueue_scripts', 'lz_cargar_cf7_condicional', 20 );Even with these filters and checks, I still see the following stylesheet being loaded on pages where no form is present:
/wp-content/plugins/contact-form-7/includes/css/styles.css
I’ve cleared all caches and tested with a default theme and no other plugins active.
Could you please confirm:
- Is there another mechanism in CF7 that forces this CSS to load?
- Is there an updated/better way to conditionally load styles and scripts only when needed?
Thanks in advance for any help!
The topic ‘CF7 CSS still loading even when form is not present (filters added)’ is closed to new replies.