video-js-for-wordpress icon indicating copy to clipboard operation
video-js-for-wordpress copied to clipboard

Load JS & CSS, When only shortcode called

Open palpalani opened this issue 12 years ago • 2 comments

WordPress 3.6 has nice feature 'has_shortcode', using this we can load scripts when they called: https://codex.wordpress.org/Function_Reference/has_shortcode

Example: function custom_shortcode_scripts() { global $post; if( has_shortcode( $post->post_content, 'videojs') ) { wp_enqueue_script( 'custom-script'); } } add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');

palpalani avatar Sep 26 '13 13:09 palpalani

Thanks for the heads up on this new feature. It will be implemented in the next version of the plugin.

nosecreek avatar Sep 29 '13 22:09 nosecreek

Unfortunately these conditional checks have created problems for some users, primarily theme and plugin authors. The problem is that has_shortcode() only checks the post content, but if do_shortcode is used by a plugin or theme outside of the main loop the scripts and stylesheets don't get loaded making video.js unusable. I'm open to suggestions as to the best way to solve this... right now my best suggestion is to call wp_enqueue_script within the shortcode itself, whithout using has_shortcode(). This will conditionally load the scripts everytime the shortcode is used, regardless of whether it is in the loop or not. This will, however, move the scripts to the footer so I'll have to add a shim to the header which will always be loaded (only 3 lines). The other issue is that this doesn't work for stylesheets, since they need to be loaded in the header not the footer. My only solution right now is to always load the stylesheets, but they are lightweight compared to the scripts, so I'm thinking this might be an acceptable tradeoff?

nosecreek avatar Mar 29 '14 16:03 nosecreek