Prince Charming
Prince Charming

Reputation: 401

jQuery $.each is really slow

I am trying to build a dynamic combo box with $.each and $('<OPTION>'), but it is really slow on IE (takes 3/4 mins to render data after server response) on firefox and other browsers it's fine.

Here is my code that builds combo

var sel = ('#myDynCmb');
$.each(dataCollection, function(key,_value) {
    sel.append($("<OPTION>").val(key).text(_value));
});

Any help appreciated.

Upvotes: 1

Views: 2816

Answers (3)

Prince Charming
Prince Charming

Reputation: 401

Try all the solutions but it was still embarrassingly slow so I have to switch it to classic javascript, new option, and it's now super fast

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

It could be a rendering issue on IE (usually slow on DOM manipulation).

You can try something like this:

var dummyList = $("<select />");
$.each(dataCollection, function(key,_value) {
    dummyList.append($("<option />").val(key).text(_value));
});
$('#myDynCmb').empty().append(dummyList.find('option'));

So you load the options into a dummy list (not in DOM), then you add all the elements into you list (in DOM).

Upvotes: 0

jbduzan
jbduzan

Reputation: 1126

Dom manipulation are usualy slow, especialy when you're appending to the dom.

One good practices is to put all your html into a var and append the content of this var to the dom, wich result in one dom opération, this is much faster

var htmlToAppend = "<select>";
$.each(dataCollection, function(key,_value) {
    select += "<option value="+key+">"+_value+"</option>";
});
htmlToAppend += "</select>";
$('#myDynCmb').empty().append(htmlToAppend);

Something like that

Upvotes: 6

Related Questions