Run JS only on pages with my widget

I’m trying to get a widget to only load javascript on a page where the widget is present.

I’ve tried adding the add action in the ‘showWidget’ didn’t work.

Read More

What am I doing wrong?

PHP

wp_register_sidebar_widget('MyWidget','MyWidget', 'showWidget');
add_action('wp_enqueue_scripts', 'addScript'); //now the script appears on every page

function addScript()
{
    wp_register_script('MyWidgetJs', plugins_url( '/script.js' , __FILE__), array('jquery'));
    wp_enqueue_script('MyWidgetJs');
}
function showWidget($args)
{
    // add_action('wp_enqueue_scripts', 'addScript'); //I tried this but it doesn't work :(
    wp_enqueue_script('MyWidgetJs');
    extract($args);
    /* do widget stuff */
}

Related posts

Leave a Reply

2 comments

  1. Seems that the new version of WordPress supports this: http://codex.wordpress.org/Version_3.3

    Register your script, but don’t enqueue it. In your widget PHP, add in the wp_enqueue_script(‘your_script_name’); and it’ll load it only when your widget is used and place it in the footer.

    You are going to upgrade to 3.3, right? 🙂

    SO, something like this should work just fine:

    wp_register_sidebar_widget('MyWidget','MyWidget', 'showWidget');
    function showWidget($args) {
        wp_enqueue_script('MyWidgetJs');
        extract($args);
        /* do widget stuff */
    }
    
  2. You want to use is_active_widget() conditional to do something like:

    <?php
    if ( is_active_widget('MyWidget') ) {
         add_action('wp_enqueue_scripts', 'addScript'); 
    }
    ?>
    

    using your above code the final widget may look like:

    <?php
     if ( is_active_widget('MyWidget') ) {
             add_action('wp_enqueue_scripts', 'addScript'); 
        }
    
    function addScript()
    {
        wp_register_script('MyWidgetJs', plugins_url( '/script.js' , __FILE__), array('jquery'));
        wp_enqueue_script('MyWidgetJs');
    }
    function showWidget($args)
    {
        wp_enqueue_script('MyWidgetJs');
        extract($args);
        /* do widget stuff */
    }