call my script only after loading UI library?

Enqueue your script instead of putting it in your template, you can enqueue your code as is, or put your code in an actual file.

The benefit of doing this is you gain control over output, as you can see there is a $priority parameter for add_action.

add_action( $hook, $function_to_add, $priority, $accepted_args );

Futhermore wp_enqueue_script comes with two parameters which can alter output, which are $deps and $in_footer.

wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );

So with the above 3 settings you can surely change the way the scripts load.

http://codex.wordpress.org/Function_Reference/wp_enqueue_script
http://codex.wordpress.org/Function_Reference/add_action