I want to speed up my site. I want to load Contact form 7 css & js only when form is one the page. I found solutions for this but they are not 100% for me. Why? Because they are based on which page I am. I want to make it another way. I'm using gutenberg to create my site and I don't know where the form will be. I could be on Contact page, on main page or on subpage in future. So my idea is load css & js only when the form is in page. Any page. So is it any way to do it? I was thinking about simple ACF Checkbox to do it. When user want to put CF7 shortcode/form he need to click checkbox for example Website have form
. Maybe there's more elegant way?
You can simply dequeue all of the Contact Form 7 Scripts and then check for the shortocde.
Add this to your functions.php from your theme:
function contactform_dequeue_scripts() {
$load_scripts = false;
if( is_singular() ) {
$post = get_post();
if( has_shortcode($post->post_content, 'contact-form-7') ) {
$load_scripts = true;
}
}
if( ! $load_scripts ) {
wp_dequeue_script( 'contact-form-7' );
wp_dequeue_script('google-recaptcha');
wp_dequeue_style( 'contact-form-7' );
}
}
add_action( 'wp_enqueue_scripts', 'contactform_dequeue_scripts', 99 );