Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jquery live slow down websites?

I have a problem I am using jquery U.I tabs that load everything with ajax. Now I have it right now everytime you click on a tab a partial view is loaded up into that tab.

Now in this partial view their are javascript files that use jquery to bind all the events that are needed in that tab plus some jquery plugins I am using.

Now every time that tab is loaded up all those scripts are loaded up. If it is clicked 10 times then those scripts are loaded 10times up meaing now each of say my buttons will now have 10 of the same events on it mean if someone clicks on that button 10 events will all fire off to and do the same thing.

So I need to find some solution to either move all the script out and have it on the main page and use jquery.live or some other solution.

I tried to do use jquery caching for the U.I tabs but this won't work since some things in say Tab A when changed effect Tab B meaning I need Tab B to be reloaded but the scripts can't reload otherwise I run into the same problem as now.

like image 254
chobo2 Avatar asked Sep 17 '09 04:09

chobo2


2 Answers

Read here for a nice presentation covering jQuery's event delegation.

After reading the above look at this:

// using jQuery 1.4.2
(function($){
    // You can cache the container you plan on using for event delegation.
    //   If using $(document).ready(...) to call the below functions
    //     your "container" element should already exist in the DOM
    //   (the .specialAjaxLink elements don't have to exist yet).
    var container = $("#container");

    // whenever an element with the class "specialAjaxLink" is clicked
    // while inside your container element execute the handler on them.
    container.delegate(".specialAjaxLink", "click", function(){
        // do something amazing...
        solveWorldHunger(this);
        // stop propagation and prevent default...
        return false;
    });
}(jQuery));

You shouldn't have to worry about performance problems when using the above method unless you are creating an app as complex as gmail, docs, or google wave.

like image 97
David Murdoch Avatar answered Sep 23 '22 03:09

David Murdoch


i always, as a rule, call unbind() before bind()

like image 40
Scott Evernden Avatar answered Sep 20 '22 03:09

Scott Evernden