开发者

Using JavaScript in WordPress: throw all jQuery plugins in, or is there a way to conditionally load?

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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜