4

I'm trying to use chosen.js for a list with about 1400 entries. It is taking about 1.5 seconds to run the initialisation code for chosen.

Have tracked down that in SelectParser.prototype.add_option() the slow part is html: option.innerHTML

 this.parsed.push({
     array_index: this.parsed.length,
     options_index: this.options_index,
     value: option.value,
     text: option.text,
     html: option.innerHTML,  // <======= here
     selected: option.selected,
     disabled: group_disabled === true ? group_disabled : option.disabled,
     group_array_index: group_position,
     classes: option.className,
     style: option.style.cssText                  
    });

If this is set to simply html: option.text the chosen plugin still seems to work as required.

Are there other implications to changing this & any other tips to improve performance?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Becki
  • 41
  • 2
  • In which browser does it take 1.5 second ? 1400 entries is really big amount of data/html, and can slow down chosen initialization significantly. You should consider ajax solution (combined with autocomplete), check this link for details: http://stackoverflow.com/questions/12044330/jquery-chosen-plugin-dynamically-populate-list-by-ajax . Some time ago I had similar performance problems and my general conclusion is: JS DOM manipulation is very slow in many browsers, the best way to avoid it is portioning data and it's interaction with frontend. – Tomasz Rozmus Oct 28 '13 at 14:17

1 Answers1

2

While HTML serialization is generally a slow operation, I find it surprising that it is supposedly responsible for more than a second delay. A quick test I've run has shown that executing option.innerHTML on 5000 options takes less than 2 milliseconds in Firefox 33 and Chrome 38, other browsers should behave similarly. So I have a suspicion that you identified the source of the issue incorrectly.

Either way, your change has two implications:

  1. Any formatting of the options will be lost, chosen.js will only display pure text. Given that most of the time options are only pure text, that might not be something you care about.
  2. The option text will be inserted as HTML code. This will cause trouble whenever special characters like < are used, this is also a potential source of security issues (XSS). To prevent this your code should contain escaping:
 html: option.text.replace("&", "&amp").replace("<", "&lt;").replace(">", "&gt;"),
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126