Shortcodes, include CSS and JS only on the correct blog pages
Not too long ago I wanted to add a new plugin to my blog. During various tests I noticed something quite shocking: at least one of the plugins insisted on loading it's CSS and jquery on every page of my blog. A little more testing showed me that many plugins do the same.
That's not good. Yes, jquery is lightweigt, CSS files aren't big, but that's not a good reason for making every visitor download them. I did some research and it doesn't look like anybody wrote about a solution yet, so here's one way. Usually, you would use wp_enqueue_script() or wp_enqueue_script().
Instead, try this:
<?php
add_action( 'wp_print_styles', 'yourplugin_include_css' );function yourplugin_include_css() {
// Check if shortcode exists in page or post content
global $post;
if ( strstr( $post->post_content, '{yourshortcode}' ) ) {
echo $csslink;
}
}?>
That's it. Please don't add custom javascript or CSS on each and every page of my blog.
Update: See this excellent post for an improved solution.
Update 2: The best solution for loading JavaScript, thanks to scribu.
This isn't true for a good made up template as you can make the template load JQuery when ever needed:
Should only load java when needed. ?
That is good, but how does the plugin know which page to load on? Using a shortcode? The post needs more explanation.
Yes, this post assumes the plugin uses a shortcode. I wrote the post in a rush and will try to make this more clear. Thanks for the remark.