clamp
clamp

Reputation: 34016

JQuery do not append on each iteration to avoid DOM redraws

i have this jquery code which probably causes DOM redraws at every step of the iteration. how can i do this only once?

$.each(d.sponsoren, function(k,v) {
        $("#sponsoren").parent().append( $("<div/>").append($("<a/>").attr("href", v.l).append($("<img/>").attr("src", v.im).css("margin","1").css("border","0"))) );
    });

Upvotes: 2

Views: 838

Answers (4)

user2882189
user2882189

Reputation: 81

The easiest solution for me was to start with a Div that has display:none, then append elements to that div, once done then set display:block. No redraw or blink effect now.

Upvotes: 0

Lucky Soni
Lucky Soni

Reputation: 6878

var markup = "";
$.each(d.sponsoren, function(k,v) {
    markup += "<div><a href='" + v.l + "'><img src='" + v.im + "' style='margin:1; border:0' /></a></div>";
});

$("#sponsoren").parent().append(markup);

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94459

Collect the elements in an array then append the array:

var elements = [];
$.each(d.sponsoren, function(k,v) {
         elements.push($("<div/>").append($("<a/>").attr("href", v.l).append($("<img/>").attr("src", v.im).css("margin","1").css("border","0")))));
    });
$("#sponsoren").parent().append(elements);

Upvotes: -1

markcial
markcial

Reputation: 9323

keep the dom node in memory until the bucle has finished, then append node in memory to the DOM

var $tempnode = $('<div />');
$.each(d.sponsoren, function(k,v) {
        $tempnode.append( $("<div/>").append($("<a/>").attr("href", v.l).append($("<img/>").attr("src", v.im).css("margin","1").css("border","0")));
});
$("#sponsoren").parent().append( $tempnode );

Upvotes: 3

Related Questions