0

So I'm attempting to populate a select tag like so, using jquery, the range I'm choosing is actually pulled from a database but this simplifies things for you:

 var select_tag = $("select");
 for(var i = 0; i < 10000; i++)
 {
      $("<option value='" + i + "'>" + i + "</option>").appendTo(select_tag);
 }

When I do this, the code take quite awhile to run and populate the select tag. So much so that a user might start to think that their browser closed and start clicking everywhere. Is there anyways I can speed the process up/optimize it so that it doesn't take this long?

Please note that the select tag itself is added to the page based on a click event, and is not loaded with the webpage right away. In this example a user is on one page, then the user clicks the 'Next' button, this triggers various functions one of which adds and populates the select element to the DOM. I just need a way to speed-up or optimize the process.

Ricky
  • 823
  • 2
  • 14
  • 31

4 Answers4

3

This is a solution.

var options = "";
 for(var i = 0; i < 10000; i++)
 {
     options += "<option value='" + i + "'>" + i + "</option>";          
 }
 $("select").append(options);
chfumero
  • 1,137
  • 2
  • 13
  • 26
0

Unfortunately, I don't think there are many "macro" optimizations you can make.
There are a few smaller optimizations you can make, though.

  1. Avoid parsing HTML -- create elements using document.createElement('option').
    See Advantages of createElement over innerHTML?
  2. Use a DocumentFragment to batch-insert all options at once.
    See http://jsperf.com/document-fragment-vs-innerhtml-vs-looped-appendchild

Here's some sample code that does this:

var select_tag = $("select");
var docFrag = document.createDocumentFragment();
for(var i = 0; i < 10000; i++)
{
  docFrag.appendChild(createOption(i, i));
}
select_tag.append(docFrag);

function createOption(text, value) {
    // Avoid parsing HTML using jQuery; use native methods instead:
    var option = document.createElement('option');
    option.textContent = text;
    option.setAttribute('value', value);
    return option;
}
Community
  • 1
  • 1
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85
0

You could remove the element from the document and add all the elements, then insert it back into the document.

var select_tag = $("select").detach();

 for(var i = 0; i < 10000; i++)
 {
      $("<option value='" + i + "'>" + i + "</option>").appendTo(select_tag);
 }

$('#orignal-location').append(select_tag);
Kyle Needham
  • 3,379
  • 2
  • 24
  • 38
0

With Huge data there is always delay . So I recommend you to use another approach, like server filtering service with a client side control such as select2 or chosen jquery plugins to handle user input

Take a look at at these 2 they have remote data loading feature .

I hope this can help.

boudiz
  • 1
  • 2