views:

26

answers:

3

I'm relatively new with WordPress theming and JavaScript, though not incompetent with either.

I'm looking to have a maximum of 10 jQuery plugins to go on the blog, but I'm wondering if there's a way to have them load only when needed, as I don't want any unnecessary loading for the users.

Something similar in something I know a little bit more of would be the conditional comments in IE <!--[IF IE]> @import ie.css <![endif]-->.

A: 

I would keep it simple.

Unless the plugins are large (over 20k in size each) I would put them all in 1 js file and load it on every page. The user should cache the file after the first hit and you only have 1 request, versus 10, on page load.

The Who
+1  A: 

Loading them when they are needed is best practice. You will want to refer to the WordPress Conditionals Codex page, which will provide documentation and examples on how to execute code on a per page basis.

For example:

if(is_page('about-us'))
{
     echo '<script type="text/javascript" src="myScript.js"></script>';
}

You can load any kind of text, code, or scripts using these conditionals on a per page, page type, and even taxonomy (categories and tags) type basis. Don't forget you can use this with logical operators to really kick it up a notch.

hsatterwhite
Thanks for this. I thought I scoured the codex and saw that page, but wasn't able to find it again.
ineedtosleep
+1  A: 

You can have jQuery itself load up new plugins, but you will need to make sure you're only trying to use them once they've been loaded. You'll want to use the $.getScript() for this, and be sure to only use your plugins starting in the callback.

$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});

Hope that helps.

Lance May
This is pretty nifty. Nice one Lance!
hsatterwhite
Thanks. I'll keep this in mind when I get some non-WordPress projects. I'm sure it'll be put to good use :)
ineedtosleep
Why non WP projects? Letting jQuery handle its scripts keeps responsibility off of the server. This can be used with PHP, ASP, HTML-just, etc. And thanks. ;)
Lance May