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 add an action to wp_print_styles or wp_print_scripts that does something like this:

add_action( 'wp_print_styles', 'yourplugin_include_css' );
 
function yourplugin_include_css() {
    echo $csslink;
}

Instead, try this:

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 so far

Share this page:
  • Twitter
  • Technorati
  • del.icio.us
  • StumbleUpon
  • Google Bookmarks
  • LinkedIn
  • Reddit
  • Facebook
  • Fark
  • Digg
  • NewsVine
  • MySpace
  • Slashdot
  • Sphinn

3 Comments

  • Posted by KillerSneak on 2009/10/22 at 19:15. Reply

    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. ?

  • Posted by Montana Flynn on 2009/12/29 at 02:45. Reply

    That is good, but how does the plugin know which page to load on? Using a shortcode? The post needs more explanation.

    • Posted by Nicolas on 2009/12/29 at 09:05. Reply

      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.

Leave a Reply

Your email is never shared. Required fields are marked *

*
*