开发者

How to optimize simple jQuery Image Slide Plugin

For a better project structure i try to store (build) all my custom jQuery stuff to plugins. Is it possible to optimize the following plugin? I know it is ;) But i need to learn...

Plugin

$.fn.slide = function(options){
    options = $.extend({
        slideitem: 'img',
        prevclass: '.prev',
        nextclass: '.next'
    }, options);

    var element = $(this);

    // How many items to slide?
    var total = element.find(options.slideitem).length;
    var count = 0;

    // Hide all items but not first item
    element.find(options.slideitem).not(':first').hide();

    // Jump to next item
    element.find(options.nextclass).click(function() {        
        (count == total - 1) ? count = 0 : count++;
        element.find(options.slideitem).hide();            
        element.find(options.slideitem).eq(count).show();
        return false;
    });

    // Jump to previous item
    element.find(options.prevclass).click(function() {
        (count == 0) ? count = total - 1 : count--;
        element.find(options.slideitem).hide();            
        element.find(options.slideitem).eq(count).show(开发者_如何学Go);
        return false;                
    });
}

Example HTML

<div id="container">
    <div id="nav"><a href="#" class="prev">Previous</a> <a href="#" class="next">Next</a></div>
    <img src="http://dummyimage.com/250x250/000/fff&text=Image#1" width="250" height="250" alt="Dummy #1"/>
    <img src="http://dummyimage.com/250x250/999/fff&text=Image#1" width="250" height="250" alt="Dummy #2"/>
    <img src="http://dummyimage.com/250x250/BBB/fff&text=Image#1" width="250" height="250" alt="Dummy #3"/>
    <img src="http://dummyimage.com/250x250/CCC/fff&text=Image#1" width="250" height="250" alt="Dummy #4"/>
</div>

Here is a working copy you can play with: http://jsfiddle.net/T4t4z/

Thank You in Advance!


There are a few basic things you can do that won't decrease readability and will most likely improve performance slightly:

  1. Cache jQuery results. You're using:

    element.find(options.slideitem)
    

    several times. You could replace this with a cached query:

    var items = element.find(options.slideitem);
    
  2. Chain jQuery operations. Instead of:

    element.find(options.slideitem).hide();            
    element.find(options.slideitem).eq(count).show();
    

    Use:

    element.find(options.slideitem).hide().eq(count).show();
    

However, I would avoid trying to optimize your code too much before you run into problems.

If you need to optimize further, check out JSPerf, which is a pretty cool tool that will compare two pieces of JavaScript for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜