Wordpress: Enqueue script only if user is logged in

Use this snippet in your wordpress plugin to load a script only if a user is logged in:

function enqueue_my_script() {
    if(is_user_logged_in()) {
        wp_enqueue_script( 'my-script', plugins_url('/my-script.js', __FILE__), false, '1.0', 'all');
    }
}

add_action( 'wp_enqueue_scripts', 'enqueue_my_script');

It does not matter how exactly you use wp_enqueue_script(), just wrap it in a

if(is_user_logged_in()) {
    // Call wp_enqueue_script() here !
}