In 2010 I wrote a tutorial for loading JavaScript using the WordPress API. The main problem was how to enqueue a script only when needed; for example, when a certain shortcode was present on the page.
Since WordPress 3.3, you can skip all the Yoda acrobatics; just call wp_enqueue_script() inside the shortcode handler:
add_shortcode('myshortcode', 'my_shortcode_handler'); function my_shortcode_handler($atts) { wp_enqueue_script('my-script', plugins_url('my-script.js', __FILE__), array('jquery'), '1.0', true); // actual shortcode handling here }
If you’re interested in the gory details, here’s the trac ticket.

Thanks Silviu-Cristian! Clean and efficient solution – just what I needed.
Thanks for this piece of code scribu.
It is quite handy and together with the code that I found here:
http://wordpress.stackexchange.com/questions/14063/is-this-a-bad-implementation-of-wp-enqueue-script-for-conditional-usage
I feel perfectly equiped for conditional script loading. :)
What about a just in time solution that prints the scripts exactly where you need them and when you need them?
http://twentyfiveautumn.com/2012/03/14/loading-javascript-on-the-frontend-with-your-wordpress-plugin/
Why wait till wp_footer?
Main reason is that the later the <script> tags are in the HTML source, the faster the perceived page load.
Thanks scribu,
I have another question. I’m putting my
wp_register_scriptinadd_action('init', 'my_function').Would there be any advantage for me to move wp_register_script to
register_activation_hook( __FILE__, 'my_install_function' )?Ray
If you do that, then that script handle will only be available when your plugin is first activated. I don’t think that’s what you want.
thanks again
I’ll stick with add_action(‘init’, ‘my_function’).
Ray
Hi scribu,
What about if I want to add a css file. Is it in the same way?
Thanks,
Carlos
Not yet because there currently isn’t wide browser support for having
<link>or<style>tags outside of<header>.It actually works in several recent browsers, but it is not according to the specification and is (currently) considered bad practice. However, it has been discussed that it might be allowed in html5 using the itemprop attribute. See
http://stackoverflow.com/questions/1642212/whats-the-difference-if-i-put-css-file-inside-head-or-body for more information.
What is the best way to add a css style to my plugin? It only will be loaded when the plugin is working.
The drawback of enqueuing (registering and enqueuing in one step) inside the shortcode definition that you can’t dequeue it.
It’s better to register the script using the wp_enqueue_scripts action hook and then enqueue it in the shortcode definition.
In this way the user can still use wp_enqueue_scripts to deregister the script and prevent enqueing if they want to include a different script.