Loading js in shortcode

Shortcode is very commonly used in WordPress sites, and a number of js and styles might be associated with it.

Loading all those shortcode specific js on each and every page will add up unnecessary load time for rest of the pages.

So you can instead load the scripts and styles conditionally.

Register script or style, you want to load dynamically:

add_action( 'wp_enqueue_scripts', 'cc_register_shortcode_script_style' );

 * Register style sheet and scripts
function cc_register_shortcode_script_style() {
	wp_register_style( 'my-shortcode-style', '/path/to/mystyle.css' );
	wp_register_script( 'my-shortcode-script', '/path/to/script.js', array(), '1.2.3', true );

And enqueue the style and scripts inside your shortcode , so that whenever the shortocde runs the scripts and styles are available on that page only.

add_shortcode('cc_shortcode', 'cc_shortcode_handler');

function cc_shortcode_handler($atts) {

	// actual shortcode handling here
 Ref: WordPress Trac Ticket

1 thought on “Loading js in shortcode”

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.