简体   繁体   中英

How to call function once with scroll function in jQuery?

I have .viewPort Area that contain large element with scroll.

And create function some thing like flowing code:

jQuery:

$('.part').each(function(){
    if( $(this).is(':in-viewport') ){
        var partID = $(this).attr('id');
        if($('.part #content-id-'+(partID)+').length < 1) {
            partLoader(partID);
        }                       
    }
});

function partLoader(id) {
    // do some ajax actions
    //$.ajax({....});
    console.log('done');
}

when I scroll I get a lot of done in console.log and the browser crashed!!!

I know that is for sending too much partLoader() to server because of scroll event!

so... how can I call partLoader once with scroll?

  1. consider not doing $('.part').each() but instead $('.part').last() (whether that works or not will depend on the structure of your site, so I can't be sure.)
  2. use .part more sparingly, so it generates less requests.
  3. use better if statements to filter out more .part elements that don't need the update.
  4. use a debouncer ...

i don't think 4 would be necessary since it looks like a structural problem with how you are calling the AJAX (from every .part element instead of ones that need it- but I can't offer much more advice without knowing more about the structure), but it's something that will limit the # of AJAX calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM