Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

functionAddToList()
{
    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.

Post a Comment for "Slow Jquery Function"