jQuery bind efficiency

前端 未结 4 861
说谎
说谎 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:46

    Bind your click event to the entire document, and within the function, look at event.target to see which product element was actually clicked on. This way you only need to do a single bind.

    0 讨论(0)
  • you should look at jqrid or flexigrid somthing that will allow you to do paging thats allot of data to output at once so it's best to limit how much you put out at once even if those things are right for your project you must figure out how to limit the data is the bottom line

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-01 22:55

    First, use the profiler built into Firebug to check where most of the delay is; just hit "profile", run your slow action, hit it again and see which calls are the most expensive.

    Second, look at "live" event handling: http://api.jquery.com/live/

    The way this works is that there's just one event handler, looking at the whole document, delegating to live event handlers. This works much faster when you have loads of elements, because you don't need to add an event handler to each element specifically.

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