Can this jQuery be modified to work faster?

This next jQuery function eachcalls IE8 to represent "Stop running script? .. A script on this page causes your browser to start slowly ..".

$('.expand-collapse-icon').each(function() {
    var dupId = $(this).parent('td').attr('duplicate-id');

    var len = $(".results-table tr")
        .filter(":not(:first)")
        .filter(":has(.hidden-row[duplicate-id='" + dupId + "'])").length;

    if (len <= 0) {
        $(this).hide();
        $(this).parent('td').css('padding-left', '15px');
    }
});

Basically, I have a number of visible lines (about 92) that have related hidden lines. Lines are connected duplicate-idEach visible line has expand-collapse-iconin the first <td>. If you click on the icon, it will display hidden lines. If the visible line has no associated hidden lines, I do not want to show the icon.

Ideally, I can prevent the page from displaying the icon on the server side if there are no related lines, but there are dragons hiding in the code.

Is there an obvious way to speed this up?

+5
3

, $(this) - "cache" . :

var $this = $(this);

script jQuery 3 - !

, - .each , , $( ". some-selector-example" ). EDIT: 10 jQuery, ( 2009 ), ( ) - . , .each .

, , , script - len = $( ". results-table tr" ). filter ( ": not (: first)" ). , ( , ):

var cached_trs = $(".results-table tr").filter(":not(:first)");

, , :

var len = cached_trs.filter(":has(.hidden-row[duplicate-id='" + dupId + "'])").length
+3

. , .hiddne-row , , , - , . :gt(0) `: not (: first) ', .

var $this, $parent, dupId, len ;

//This line will get all the rows from .resutls-table 
//filtered by ":not(:first):has(.hidden-row)"
//That way you dont have to search for trs and filter it everytime in the loop
var $resultsTr = $(".results-table tr.hidden-row:gt(0)");

$('.expand-collapse-icon').each(function() {
    $this = $(this);
    $parent = $this.parent('td');
    dupId = $parent.attr('duplicate-id');

    len = $resultsTr
        .filter("[duplicate-id='" + dupId + "'])").length;

    if (len <= 0) {
        $this.hide();
        $parent.css('padding-left', '15px');
    }
});
+2

You are using too many of the same jQuery selectors.

You can optimize by storing the one you use more than once in a variable.

$('.expand-collapse-icon').each(function() {

    var $this = $(this);
    var $parent = $this.parent('td');
    var dupId = $parent.attr('duplicate-id');

    var len = $(".results-table tr")
        .filter(":not(:first)")
        .filter(":has(.hidden-row[duplicate-id='" + dupId + "'])").length;

    if (len <= 0) {
        $this.hide();
        $parent.css('padding-left', '15px');
    }

});
0
source

All Articles