wp-recaptcha-integration icon indicating copy to clipboard operation
wp-recaptcha-integration copied to clipboard

Conditionally load js

Open stopspazzing opened this issue 9 years ago • 1 comments

Common "best practice" is to conditionally load JS only when needed. I noticed this plugin loads all js on all pages without remorse. Do you mind preventing plugin from loading on pages without shortcode, or login, etc?

Example code I use to conditionally load only when posts contain shortcode. Can be adapted to include all pages that your plugin checks pretty easy:

function gplusvid_check_function() {
    global $post;

    if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'recaptcha') ) {
        add_action ('wp_head', 'add_recaptcha_css_function');
    }
}
add_action('wp_enqueue_scripts', 'recaptcha_check_function');

stopspazzing avatar May 29 '15 01:05 stopspazzing

Yes, conditional script loading would be a good thing to have. The hard thing is to reliably detect if the scripts should be loaded or not. A captcha can be almost an every page (through a ninja or cf7 form or widget), on an archive page, comment form, etc. not to mention login and registration forms like the ones from BBPress, woocommerce etc. The only reliable way I can imagine would be to set some instance variable in the main class to true once a captcha html is generated, and then print the scripts in the footer when this var is true. I'll give it a try, once I got some spare time...

mcguffin avatar May 29 '15 06:05 mcguffin