cdub
cdub

Reputation: 25711

Slow JQuery function

I have a function like this in JQuery and JS. I have a list of divs with checkboxes and am adding them to my list. This works fine for like 40 divs, but sometimes I have 2,000 and it crashes Chrome and crawls on FF. Anyway to make this faster?

function AddToList()
{
    $('div[name="notadded"] input:checked').each(function(index)
    {
        var html = $(this).parents('div[name="notadded"]').html();

        //get rid of the class that is used to gather checkboxes in select/deselect
        html = html.replace('listvars', 'addedvars');

        var var_id = $(this).attr('value');

        var new_html = '<div id="added_' + var_id + '" name="added">' + html + '</div>';

        //hide the one we are adding and remove the check
        $(this).parents('div[name="notadded"]').hide();
        $('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);

        //add the vars to the added list
        $('.addedList').append(new_html);

        step3 = '3b';
    });
}

Upvotes: 0

Views: 157

Answers (1)

Mike Robinson
Mike Robinson

Reputation: 25159

You're doing 2000 DOM manipulations, not a good way to go. Trying doing 2,000 string manipulations and one DOM insert.

function AddToList()
{
    var new_html = "";

    $('div[name="notadded"] input:checked').each(function(index)
    {
        var html = $(this).parents('div[name="notadded"]').html();

        //get rid of the class that is used to gather checkboxes in select/deselect
        html = html.replace('listvars', 'addedvars');

        var var_id = $(this).attr('value');

        var new_html += '<div id="added_' + var_id + '" name="added">' + html + '</div>';

        //hide the one we are adding and remove the check
        $(this).parents('div[name="notadded"]').hide();
        $('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);

        //add the vars to the added list   
        step3 = '3b';
    });

    $('.addedList').append(new_html);
}

Also, from experience, unchecking 2,000 checkboxes is seriously performance intensive. I'll wager taking this line out:

$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);

Will change everything. I'd recommend rewriting this function as a string replace, it'll be a hell of a lot faster that way.

Upvotes: 2

Related Questions