NewBoy
NewBoy

Reputation: 1144

optimising javascript browser resizer for webkit browsers

I'm going to keep this short and sweet. In webkit browsers, there seems to be a slow response with the auto resizer function I have applied to [my site][1] things only seem to come into to place when the browser has been adjusted. Below is a snippet of my JS.

function setTheHeight() {

    if( $('.col-small, .img_hover').length ) {
        //Get value of highest element
        var maxHeight = Math.max.apply(Math, $('.col-small, .img_hover').map (
            function() {
                var totalHeight = 0;

                $(this).children().each(function() {
                    totalHeight += $(this).outerHeight(); 
                });

                return totalHeight;
            }
        ));
        console.log(maxHeight);
        $('.col-small, .img_hover').height(maxHeight);
    }   
}

setTheHeight();

$(window).resize(function() {
    setTheHeight();
});

Am I missing something ??

Upvotes: 1

Views: 118

Answers (1)

r043v
r043v

Reputation: 1869

try optimising, no need to recompute some times the

$('.col-small, .img_hover')

like the

.children()

also try reduce the use of map and each

maybe a thing like that ? :

var elems = [], $elems = $('.col-small, .img_hover');

$elems.each(function(i){
    var $t = $(this);
    var $c = $t.children();
    elems[i] = { $:$t, $c:$c, nb:$c.length };
});

function getHeight(e,i){
    var total=0,n=0;
    while(n < e.nb)
        total += e.$c.eq(n++).outerHeight();
    return total;
}

function setTheHeight(){
    $elems.height( Math.max.apply(Math, $.map(elems,getHeight)) );
}

$(window).resize(setTheHeight).resize();

$elems.find("img").on("load",setTheHeight);

you can also try not done the effective resize at each pixel change

var timer = false;
$(window).resize(function(){
    if(timer !== false) return; // or clearTimeout(timer);
    timer = setTimeout(function(){
        setTheHeight();
        timer = false;
    },20); // 20ms => 50fps max
}).resize();

fiddle => http://jsfiddle.net/r043v/HvmmM/

Upvotes: 1

Related Questions