Only execute jQuery function(on document ready) on the page has shortcode from plugin

This question already has an answer here:

  • Including javascript for a shortcode

    2 answers

Solutions Collecting From Web of "Only execute jQuery function(on document ready) on the page has shortcode from plugin"

You can wp_enqueue_script in your shourtcode. Here are the code I fixed.

Register your JS file

function wh_enqueue() {
    wp_register_script( 'wh-ajax-app', WH_PATH . '/js/write-here-ajax.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wh_enqueue' );

and enqueue in your shortcode function

function ajax_write_here(){
    wp_enqueue_script( 'wh-ajax-app' ); // Enqueue your script here
    $output = '<div id="write_here_ajax_wrap"></div>';
    return $output;
}
add_shortcode('write-here-ajax', 'ajax_write_here');

This will only load your JS file on the page has shortcode inserted.