You can use the function is_active_widget . E.g.:
function check_widget() {
if( is_active_widget( '', '', 'search' ) ) { // check if search widget is used
wp_enqueue_script('my-script');
}
}
add_action( 'init', 'check_widget' );
To load the script in the page where the widget is loaded only, you will have to add the is_active_widget() code, in you widget class. E.g., see the default recent comments widget (wp-includes/default-widgets.php, line 602):
class WP_Widget_Recent_Comments extends WP_Widget {
function WP_Widget_Recent_Comments() {
$widget_ops = array('classname' => 'widget_recent_comments', 'description' => __( 'The most recent comments' ) );
$this->WP_Widget('recent-comments', __('Recent Comments'), $widget_ops);
$this->alt_option_name="widget_recent_comments";
if ( is_active_widget(false, false, $this->id_base) )
add_action( 'wp_head', array(&$this, 'recent_comments_style') );
add_action( 'comment_post', array(&$this, 'flush_widget_cache') );
add_action( 'transition_comment_status', array(&$this, 'flush_widget_cache') );
}