Optimizing jQuery for Tabs

Posted by jpdbaugh on Stack Overflow See other posts from Stack Overflow or by jpdbaugh
Published on 2010-06-10T16:33:22Z Indexed on 2010/06/10 17:02 UTC
Read the original article Hit count: 298

I am in the process of developing a widget. The widget has three tabs that are implemented in the following way.

<div id="widget">
    <ul id="tabs">
        <li><a href="http...">One</a></li>
        <li><a href="http...">Two</a></li>
        <li><a href="http...">Three</a></li>
    </ul>

    <div id="tab_container">
        <div id="tab_content">
            //Tab Content goes here...
        </div>
    </div>
</div>

// The active class is initialized when the document loads 
$("#tabs li a").click(function()
{
$("#tabs li.active").removeClass("active");
    $("#tab_content").load($(this).attr('href'));
    $(this).parent().addClass("active");

    return false;   
});

The problem I am having is that the jquery code that have written is very slow. If the user changes tabs quickly the widget gets behing and bogged down. This causes the tabs to to not align with the data being displayed and just general lag. I believe that this is because the tab is being changed before $.load() is finished. I have tried to implement the following:

("#tabs li a").click(function()
{
$("#tabs li.active").removeClass("active");
    $("#tab_content").load($(this).attr('href'), function (){
        $(this).parent().addClass("active");
    });

    return false;   
});

It is my understanding that the callback function within in the load function does not execute until the load function is completed. I think this would solve my problem, however I can not come up with a way to select the correct tab that was clicked within the callback function. If this is not the way to do this then what is the best way implement these tabs so that they would stop loading an old request and load the newest tab selection by the user?

Thanks

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-ajax