enqueue script only if it is not already enqueue

I want to include a script in a shortcode output, so I am trying this:

function my_shortcode( $atts, $content = null ) {
    extract(shortcode_atts(array(
            'title'  => '',
           ), $atts));

    wp_enqueue_script('custom-script'); 

}

I have registered the script already and enqueue it if the above shortcode is used.
However I want to include the file only once, even if the shortcode is used multiple times. Currently, if the shortcode is used multiple times, it will include the script for each time. Is it possible?

Related posts

2 comments

  1. The WordPress enqueue system should prevent the inclusion of the same script multiple times, and does when I test it. For example, the following enqueues a Core script and echos a counter. If I put this shortcode into a post 4 times, I get “0123” but the media script only loads one time. The same test works with several other scripts I tried.

    function my_shortcode( $atts, $content = null ) {
        extract(shortcode_atts(array(
                'title'  => '',
               ), $atts));
        static $counter = 0;
        echo $counter++;
        wp_enqueue_script('wp-mediaelement'); 
    
    }
    add_shortcode('enq','my_shortcode');
    

    If you are getting the same script loaded over and over, there is a problem with your site, but I am not sure where start guessing at what.

  2. You can use wp_script_is() to determine if a script is enqueued – and use it in a conditional, like this:

    if( ! wp_script_is( 'custom-script', 'enqueued' ) ) {
        // your code here
    }
    

    wp_script_is() takes two parameters$handle and $list – the latter can be: registered, enqueued/queue, done or to_do; and it returns true or false.

Comments are closed.