jQuery bind efficiency

前端 未结 4 865
说谎
说谎 2021-02-01 22:01

I\'m having issue with load speed using multiple jQuery binds on a couple thousands elements and inputs, is there a more efficient way of doing this?

The site has the

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-01 22:52

    You are binding a handler 2500 times, instead make your function use either live or delegate like this:

    $('li.product-code').live('click', function(event){ 
    $('input.product-qty').live('keyup', function(){ 
    

    .live() listens for the click to bubble up at the DOM level then executes the event with the context of the click source. This means you have one event handler instead of 2500 of them, meaning it's much faster and easier on the browser.

    If you have a container that wraps the replaced content that isn't replaced (remains across all AJAX calls), you can make it more local like this:

    $('#container').delegate('li.product-code', 'click', function(event){ 
    $('#container').delegate('input.product-qty', 'keyup', function(){ 
    

    The result of this is the event bubbles fewer times before being caught.

    Another pain point is probably the creation of the elements, can you post that code? There are often easy optimizations that yield a big performance boost there.

    Update

    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live() - JQuery Docs

提交回复
热议问题