Background
I developed a jQuery-based shuttle widget for HTML select
elements because I could not find one that was minimally codified and offered a regular expression filter that compensated for diacritics.
Problem
When a few thousand entries are added to the select
, the regular expression filter slows to a crawl. You can see the problem as follows:
- Browse to: http://jsfiddle.net/U8Xre/2/
- Click the input field in the result panel.
- Type any regular expression (e.g.,
^a.*ai
).
Code
I believe the culprit is lurking here:
var options = $src.empty().scrollTop( 0 ).data( "options" );
var search = $.trim( $input.val() );
var regex = new RegExp( search, 'gi' );
var len = options.length;
var $html = $(document.createElement( 'option' ));
for( var i = 0; i < len; i++ ) {
var o = options[ i ];
if( o.text.dediacritics().match( regex ) !== null ) {
$src.append( $html.clone().text( o.text ).val( o.value ) );
}
}
$src.css( 'width', $input.width() + 4 );
Where $src
is the source $('#select')
and String.prototype.dediacritics
is defined as in the fiddle. The code above runs for every single keypress. There is one more relevant snippet:
// Create a copy of the source options to use when matching the regex.
var $options = [];
$src.find( "option" ).each( function() {
$options.push( { value: $(this).val(), text: $(this).text() } );
});
$src.data( "options", $options );
This makes a copy of the options from the source list, but only runs once. (This results in a duplication bug when shuttling options, but adding the above code into the input
event handler would slow the filter even more.)
Question
How can the code be made to perform regular expression filtering on lists up to 5,000 words in nearly real-time?
Thank you!