video-js-for-wordpress
video-js-for-wordpress copied to clipboard
Load JS & CSS, When only shortcode called
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');
Thanks for the heads up on this new feature. It will be implemented in the next version of the plugin.
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?