Search code examples
jqueryhtmlcrashgenerated-code

JQuery filling an option tag with a lot of data makes browser crash


When I use the following code

var html = "";
$.map(data.modelTypes, function (item) {
    html+= "<option>" + item.type + "</option>";
});
$("#drowdown").html(html);

there is so much HTML my javascript has to add to the $("#dropdown") element it makes any browser crash for a couple of seconds, in the end it works as it should and fills up the dropdown list but is there anyway of making my browser not crash?


Solution

  • Don't concatenate a huge string that has to be parsed, create the actual elements and put in the select:

    var options = $.map(data.modelTypes, function (item) {
      return $('<option>', { text: item.type })[0];
    });
    $("#drowdown").empty().append(options);
    

    Note: You were using the map method as each, you should return the value in the function, then you get an array of the values returned from the map method.

    Edit:

    Some testing shows that using more plain Javascript instead of using jQuery to loop and create elements makes it twice as fast:

    var options = [];
    for (var i =0; i < data.modelTypes.length; i++) {
      var o = document.createElement('OPTION');
      o.text = data.modelTypes[i].type;
      options.push(o);
    }
    $("#drowdown").empty().append(options);
    

    On my computer in Firefox this adds 1000000 option elements in around a second.

    Anyhow, if you have so many options, you should probably rethink the UI...