Mohsen Rasouli
Mohsen Rasouli

Reputation: 352

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?

Upvotes: 0

Views: 148

Answers (1)

serakfalcon
serakfalcon

Reputation: 3531

  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.

Upvotes: 1

Related Questions