Pierre,
The way I handle this is with wp_enqueue_script and wp_dequeue_script, and use a instance variable $is_active in the Your_Widget class
So do the wp_enqueue_script based on is_active_widget which enqueues the script on all pages but with the footer parameter set to true. Note the dequeue is run at a priority to make sure it runs before the scripts are output.
function enqueue_scripts() { if ( is_active_widget( false, $this->id, $this->id_base, true ) ) { wp_enqueue_script( 'your-script-handle', 'your-script-url', array(), '1.0', true ); add_action( 'wp_footer', array($this,'dequeue_redundant_scripts'), 1 ); }
}
Then in the widget function indicate if the widget is active on that page
function widget( $args, $instance ) { // outputs the content of the widget $this->is_active = true; }
Then in the footer dequeue the script if the widget is not active on that page
function dequeue_redundant_scripts() { if (! $this->is_active) { wp_dequeue_script('your-script-handle'); } }
This approach of enqueue then dequeueing if unused also works well for plugins that define shortcodes which require scripts