jQuery's .each slower on Safari than Chrome/Firefox

后端 未结 1 520
醉酒成梦
醉酒成梦 2021-01-24 23:57

I have a large HTML table (1,000-1,500 rows, 40 cols wide). I have a few input and select boxes so users can filter rows. The relevant javascript/jquery (note: not entire code

相关标签:
1条回答
  • 2021-01-25 00:54

    After removing all the repetition and unnecessary complication from your code, this is what remains:

    var colRank = 0, colTeam = 1, colGP = 2, colAge = 3, colPos = 4;
    
    function filterTable() {
        var minGP = +$("#mingp").val();
        var age = +$("#age").val();
        var teams = $("#teamFilter").val().toUpperCase();
        var position = $("#position").val();
        var rank = 0;
    
        $("#myTablePlayers .playerData").each(function () {
            if (
                (teams && this.cells[colTeam].textContent.toUpperCase().includes(teams)) ||
                (minGP && +this.cells[colGP].textContent < minGP) ||
                (age && (+this.cells[colAge].textContent < age || +this.cells[colAge].textContent >= age+1)) ||
                ((position === "D" || position === "F") && this.cells[colPos].textContent.indexOf(position) === -1) ||
                (!(position === "D" || position === "F") && (this.cells[colPos].textContent !== position))
            ) {
                this.cells[colRank].textContent = ++rank;
                this.style.display = "";
            } else {
                this.style.display = "none";
            }
        });
    }
    

    I've already removed almost all jQuery in favor of native DOM manipulation.

    The remaining .each() could be tuned into a plain old for loop over the document.getElementById('myTablePlayers').tBodies[0].rows, if you want to squeeze out the last bit of possible performance.

    Reorder the if conditions by likeliness: From the one that will typically filter out the most rows to the one that will filter out the least rows. Because JS short-circuits conditions, this way less conditions are checked overall.

    Making the table display: fixed can also improve render performance at the expense of flexibility.

    Finally, you can use CSS to do counters. This is probably faster than manually setting the contents of a table cell. Test for yourself.

    0 讨论(0)
提交回复
热议问题