Reputation: 97
I'm creating a select List from a getJson call.
in firefox / chrome the select list is generated very quickly but in ie (tested in ie8) it takes some seconds to create the options.
There is approx 2000 options being added to the select list
My code is below
function getPractitioners(practID, selectID) {
selectID = '#' + selectID;
$.getJSON("/practitioner/getPractitioners", { practID: practID }, function (fooList) {
$(selectID).empty();
$.each(fooList, function (i, foo) {
if (foo.profID == practID) {
$(selectID).append(('<option value=\'' + foo.profID + '\' selected=\'selected\'>' + foo.display + '</option>'));
}
else
{
$(selectID).append(('<option value=\'' + foo.profID + '\' >' + foo.display + '</option>'));
}
});
$(selectID).trigger("liszt:updated");
});
}
Can anybody suggest anything to improve this?
Previously I was adding the options like
$(selectID).append(("<option></option>").attr("value", foo.profID).attr("selected", "selected").text(foo.display));
but changing this did not improve the performance.
Thank you in advance.
Upvotes: 0
Views: 719
Reputation: 1
I have the same issue. I improve performance by manipulating selected attribute after appending all options.
//slow --- append selected value in each apppend.
$.each(fooList, function (i, foo) {
$(selectID).append(('<option value="XXX" selected>yyyy</option>'));
});
//fast --- manipulating selected attribute after append to DOM
$.each(fooList, function (i, foo) {
$(selectID).append(('<option value="XXX">yyyy</option>'));
});
$(selectID).find("option").attr("selected", "selected");
But I don't know why this workaround works well.
Upvotes: 0
Reputation: 97
This plugin https://github.com/harvesthq/chosen/pull/1339 resloves the exact issue that I have been having with the chosen plugin.
Upvotes: 0
Reputation: 33661
Use a string and append once at the end of the loop to reduce the amount of dom manipulations you are doing.
var options = '';
$.each(fooList, function (i, foo) {
options += '<option value=\'' + foo.profID + '\' >' + foo.display + '</option>';
});
$(selectID).html(options).val(practID).trigger("liszt:updated");
Upvotes: 2