这个响应式表JS代码可以提高性能吗?

时间:2015-12-23 11:27:29

标签: javascript jquery

这是一个有效的JS fiddle

我只是想知道我是否应该做些什么来提高代码的性能?

在此之前我使用的是dataTables.net的响应式插件,我很高兴地说我的(更简单的)代码运行速度比它快5倍。在我的机器上,如果我使用DT响应,那么小提琴平均大约50ms而不是250ms。

但它可以变得更好吗?我是JS专家的FAR,我确信它会显示出来。如果没有它可以做得更好,我很高兴放弃jQuery!

function initResponsiveTables() {
    //does this enhance performance at all?
    'use strict';

    //get an array of <th> elements
    var th = $('th');

    //initialise in top scope
    var priorities = [];

    //iterate over the <th>s, extracting their column priorities
    th.each(function (index) {
        var priority = th[index].getAttribute('data-priority');

        //TODO: this seems very messy, I feel there must be a cleaner way?
        if (priorities[priority] === undefined) {
            priorities[priority] = index;
        } else {
            priorities[priority] += ',' + index;
        }
    });

    //clean up the array so we have consecutive indices
    priorities = priorities.filter(function (x) {
        return x !== undefined && x !== null;
    });

    //initialise all of these outside of the loop
    var sCols = '';
    var aCols = [];
    var aSelectors = [];
    var sSelectors = '';
    var i;

    //while the table is wider than the window, and there's still columns to remove
    while ($('#table').width() > $(window).width() - 40 && priorities.length > 0) {
        //get the lowest priority
        sCols = (priorities.pop() + '');

        //split it, in case we have more than one column on the same priority
        //in this case we prefer to remove them as a group, rather than one at a time
        aCols = sCols.split(',');

        //clear the array from previous iteration
        aSelectors = [];
        for (i = 0; i < aCols.length; i++) {
            //build up the jQuery selectors
            aSelectors.push('td:nth-child(' + aCols[i] + '), th:nth-child(' + aCols[i] + ')');
        }

        //make jQuery selector string
        sSelectors = aSelectors.join(', ');

        //hide relevant columns
        $(sSelectors).css('display', 'none');
    }
}

var start = performance.now();;

initResponsiveTables();

alert(performance.now() - start);

谢谢!

0 个答案:

没有答案