user663724
user663724

Reputation:

Is it possible to avoid unnecessary ajax calls for this scenario .

This is a performance related question . I have got a Jquery collapsible div with two headers namely Hai and Label2 .

When clciked on the header , i am making a backend call , fetching the data and attaching to it .

My question if the same label is clciked again and again , i am making a Ajax call for the same thing again and again .

For example if i clcik on Hai twice (i am making twice ajax calls )

Is it possible to avoid this ?

This is my code

 $('.my-collaspible').on('collapsibleexpand', function () {

     var location_name = $(this).attr('data_attr');

     backendAjaxcall(location_name);


 });

 function backendAjaxcall() {
     // ajax call here 
 }

This is my fiddle

http://jsfiddle.net/41w8b23q/4/

Upvotes: 0

Views: 74

Answers (2)

samjudson
samjudson

Reputation: 56873

You could simply unbind the event on the first click, like so:

$('.my-collaspible').on('collapsibleexpand', function () {
    // your code
    ...
    // remove event
    $(this).off('collapsibleexpand');
});

You might want to use a namespace so you only remove your own code:

$('.my-collaspible').on('collapsibleexpand.myajax', function () {
    // your code
    ...
    // remove event
    $(this).off('collapsibleexpand.myajax');
});

http://jsfiddle.net/41w8b23q/5/

Upvotes: 2

Linesofcode
Linesofcode

Reputation: 5903

@samjudson answer is way better than mine, but in order to show you how to accomplish what I've told you in comments:

var isAjaxLoaded = false;

function loadItems(){

  // Stops if the ajax is already loaded
  if(isAjaxLoaded == true){ return; }

  // otherwise, retrieves the content and updates the flag
  $.post(url, function(response){
     isAjaxLoaded = true;
  }
}

Besides this, you may want to take a look at the function .done() of jQuery to achieve a better precision in terms of when the content from ajax is completed.

Upvotes: 0

Related Questions