Is there any way to speed up this solution for a case-insensitive jQuery :contains selector?

前端 未结 5 1090
萌比男神i
萌比男神i 2021-02-09 14:11

I found this solution for a case-insensitive jQuery :contains selector on StackOverflow. It works great, however it comes at the cost of performance. Does anyone el

相关标签:
5条回答
  • 2021-02-09 14:23

    You could try to check the selector only once, after the user has stopped typing for a specified amount of time, not for every keystroke.

    For example, a simple implementation:

    Usage:

    $("#textboxId").keyup(function () {
      typewatch(function () {
        // executed only 500 ms after the user stopped typing.
      }, 500);
    

    Implementation:

    var typewatch = function(){
        var timer = 0;  // store the timer id
        return function(callback, ms){
            clearTimeout (timer);  // if the function is called before the timeout
            timer = setTimeout(callback, ms); // clear the timer and start it over
        }  
    }();
    
    0 讨论(0)
  • 2021-02-09 14:28

    you could try not checking after each keystroke, but maybe a second after the last keystroke has been pressed. this way you're not constantly checking while the user is typing but rather checking when the user is finished or pausing typing.

    0 讨论(0)
  • 2021-02-09 14:34

    I found another solution of the case-insensitive search on Google (see Eric Phan) which varies slightly from the one I was originally using.

    Original:

    return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
    

    EricPhan:

    return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
    

    Comparing the two, you can see Eric Phan's solution accesses the DOM attributes directly and uses toLowerCase() instead of toUpperCase(). The latter doesn't really matter, but the former is what really improved the performance of the case-insensitive search. Just changing the original solution to use (a.textContent || a.innerText || "") instead of jQuery(a).text() made all the difference!

    Now I'm a bit curious, so here's a follow up question: What's the deal with jQuery.text()? Why's it so slow? I have my assumptions, but I'd love to hear what the experts have to say.

    Lastly, thanks to everyone who responded. I appreicate your help. =)

    0 讨论(0)
  • 2021-02-09 14:39

    here's a follow up question: What's the deal with jQuery.text()? Why's it so slow?

    I suspect that it's slow due to the $(a) (converting the DOM element to a jQuery object) and not the .text().

    0 讨论(0)
  • 2021-02-09 14:40

    To add to what jason has said, you can try using this plugin to accomplish that.

    0 讨论(0)
提交回复
热议问题