I wrote the following script for a page which has been loaded with a data set of about 1000 items (all in one server call–no AJAX). On each keyup the script converts the text input into a CSS-standards-friendly string (removes spaces, downcases, etc.), then matches that string with CSS classes that I’ve loaded each item with, and adjusts the “hide” or “show” accordingly for that element.
$(document).ready(function(){
$('ul.players li').hide();
$("#filter-input").keyup(function () {
var lowercase = $(this).val().toLowerCase();
var spaced = lowercase.replace(/[ _]/, '-');
var outputString = spaced.replace(/[^a-z-]/i, '');
$('ul.players li').hide();
$('ul.players li[class*="'+outputString+'"]').show();
});
});
Example of HTML this is working on:
<form>
<input id="filter-input" type="text" />
</form>
<ul class="players">
<li class="firstname lastname teamname position cityname">
<div>Basic player info here...</div>
</li>
</ul
The script is working just fine (in the simple capacity that I need it to work)–but it’s very laggy. What can I do to optimize this for performance?
(Obviously, there are a lot of class switches across those many elements–I don’t think I can avoid that–but maybe there’s something to be done about the string conversions)
You can try to insert a
<style>element in the head that matches them – this will be a lot quicker.When a key is pressed – edit this style:
Note that you might have to use
.text()to replace the contents – haven’t tried it.Just to mention that you will need some more CSS to hide all
ul.players liand show only the needed with the trick above. I think this will be fast enough, since the browser will be doing the showing and hiding.