Using wp_enqueue_script on shortcode function handler

I have this code

function this_is_my_shortcode(){
    wp_register_script('per-pas-belanja-online', plugins_url('js/per-pas-belanja-online.js', __FILE__), array('jquery'), '1.0.0');
    wp_enqueue_script('per-pas-belanja-online');
    return '<div id="poppedout">Blah</div>';
}
add_shortcode('bubba', 'this_is_my_shortcode');

The div is appear on the page, but the script is not. What mistake i have done ?

Related posts

Leave a Reply

3 comments

  1. Straight from the Codex

    Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to troubles.

  2. You should enqueue scripts like this:

    function this_is_my_shortcode(){
        add_action('wp_enqueue_scripts', function() {
            wp_register_script('per-pas-belanja-online', plugins_url('js/per-pas-belanja-online.js', __FILE__), array('jquery'), '1.0.0');
            wp_enqueue_script('per-pas-belanja-online');
        });
        return '<div id="poppedout">Blah</div>';
    }
    add_shortcode('bubba', 'this_is_my_shortcode');