How can I optimize jQuery functions for a large amount of HTML elements
I work on a climate model and I display it on a map grid. I have to use a large grid : 39x60.
So I have to manage 2340 <div>
with jQuery. I want to use a jQuery slider to zoom in / out with this :
$("#zoom_slider").slider({
orientation: "vertical",
value: 1,
min: 1,
开发者_JAVA技巧 max: 10,
step: 1,
slide: function( event, ui ) {
$('.case').css('width', function(index) {
return index * ui.value;
});
$('.case').css('height', function(index) {
return index * ui.value;
});
}
});
Each cell is built as this example :
<div id="c13_53" class="case line_13 col_53" style="width: 17px; height: 17px; top: 216px; left: 937px;"></div>
But firefox crashes when the function is executed.
Is there a way to fix this problem ?
One inefficiency in your code is that you're re-selecting every div
on every slide
event twice. $('.case')
forces the scan of the entire DOM. You should cache the elements in a variable and reuse that variable instead of re-scanning constantly.
Another inefficiency may be that multiple slide
events could be getting fired as you slide; putting a throttle on your handler could speed things up.
Was it your intention to set each one larger by what index it has? That will mean no matter which way the slider goes they will get bigger, much bigger. Better to store a reference value I think.
//Size in pixels.
var originalSize = 20,
cases = $('.case');
stop: function(_, ui) {
var size = ui.val * originalSize;
cases.css({width: size + 'px', height: size + 'px'});
}
Used stop as per Jacobs suggestion. This will at least make it more efficient, as to whether it stops crashing, no idea.
精彩评论