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.

Published on Oct. 21, 2009 at 12:23 p.m. by Nicolas and tagged WordPress, plugin, JavaScript, development, CSS. You can follow the discussion with the comment feed for this post.

3 comments

  • avatar
    KillerSneak wrote this comment on Oct. 22, 2009, 7:15 p.m.
    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. ?
    Reply to this comment
  • avatar
    Montana Flynn wrote this comment on Dec. 29, 2009, 2:45 a.m.
    That is good, but how does the plugin know which page to load on? Using a shortcode? The post needs more explanation.
    Reply to this comment
    • avatar
      Nicolas wrote this comment on Dec. 29, 2009, 9:05 a.m.
      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.
      Reply to this comment

Start a new thread

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.