在调整大小时优化计算多个div宽度的最佳方法是什么?

时间:2016-08-03 22:32:37

标签: javascript jquery performance resize

对于这个例子,在调整大小时,我需要知道如何计算一堆div的宽度。

我想以最绝对的高效方式做到这一点。想象一个极端的例子,从页面上的10个div到10,000个div。

这是jQuery问题的基本示例:

$justABunchOfParentDivs = $('.class-matching-500-elements-on-a-page');
$(window).resize(function() {

    $justABunchOfParentDivs.each(function() {
        $(this).attr('data-width', $(this).width());
    });

});

我需要一个jQuery解决方案,但也希望看到超快的非jQuery解决方案。

2 个答案:

答案 0 :(得分:3)

为了提高性能,您可以使用window.requestAnimationFrame,如下所示:

$(window).resize(function() {
  window.requestAnimationFrame(function () {
    $justABunchOfParentDivs.each(function() {
            $(this).attr('data-width', $(this).width());
    });
  });
});

仅在浏览器需要时才会触发代码(对FPS更好)。 此外,如果您使用标准API,它也会提高性能:

$justABunchOfParentDivs = document.querySelectorAll('.class-matching-500-elements-on-a-page');

window.onresize = function() {
  window.requestAnimationFrame(function () {
    Array.prototype.forEach.call($justABunchOfParentDivs, function(element) {
            element.setAttribute('data-width', element.offsetWidth);
    });
  });
};

答案 1 :(得分:0)

为Max的答案添加了debouncing。原始JavaScript:

var query = document.querySelectorAll('.class-goes-here'),
    delay = 250,
    timeout = false;

window.addEventListener('resize', function() {
    clearTimeout(timeout);
    timeout = setTimeout(function() {
        window.requestAnimationFrame(function () {
            Array.prototype.forEach.call(query, function(element) {
                  element.setAttribute('data-width', element.offsetWidth);
            });
        });
    }, delay);
});
相关问题