envysea
envysea

Reputation: 1031

What's the best way to optimize calculating multiple div's width on resize?

For this example, on resize, I need to know how to calculate the width of a bunch of divs.

I want to do this in the most absolute performant way possible. Think like an extreme example from just 10 divs to 10,000 divs on a page.

Here's a basic example in jQuery of the issue:

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

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

});

I need a jQuery solution, but would also like to see non-jQuery solutions that are super fast.

Upvotes: 0

Views: 408

Answers (2)

envysea
envysea

Reputation: 1031

Added debouncing to Max's answer. Raw 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);
});

Upvotes: 0

Max
Max

Reputation: 1844

To improve performance a little bit you can use window.requestAnimationFrame like this:

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

It fires your code only when the browser wants that (better for FPS). Also if you will do it using standard API it will increase performance as well:

$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);
    });
  });
};

Upvotes: 3

Related Questions