MarcoMagnano
MarcoMagnano

Reputation: 3

Website loses performance after some jQuery $.ajax calls

I admit I'm quite noob with full ajax websites, and so I'm surely making some mistakes.

The problem is this: in http://lamovida.arabianessence.com

every page is loaded with an $.ajax call using this function

function getAjaxPage() {
  $('a.ajaxc').click(function() {
$("li.page_block").find(".wrapper").fadeOut(400).remove();
  hideSplash();
  var $thishref = $(this).attr('href'),
      $thisurl = $thishref.replace("#!/",""),
      $urlArr = $thisurl.split('-'),
      $urlOk = $urlArr[0],
      $dataOk = $urlArr[1];

      $.ajax({
        url : $urlOk + ".php",
    data :  'id='+$dataOk,
    success : function (data,stato) {
      $("#content").css({opacity:1}).fadeIn(400);
      $("li.page_block").html(data);
      $("li.page_block").css('visibility', 'visible');
      $("li.page_block").find(".wrapper").css({opacity:0}).show().animate({opacity:1},1000);

                var $whgt = $(".wrapper").height(),
                    $ctop = ( ( $(window).height() - $whgt ) /2 )-40;

                $("#content").stop().animate({height: $whgt+40, top: $ctop},1000);
                $("li.page_block").css('padding-top',20);

                $('.scrollable').jScrollPane();
                $('.slider>ul>li').jScrollPane();

                getAjaxPage();
            },
            error : function (richiesta,stato,errori) {                     
                alert(errori);
            }
        });
  });
}

Every time this function is called the content gets loader slower, and after about 20 clicks things get real bad, and the loading time grows and grows.

I tried to analyze the situation using the Google Chrome's Timeline, and I saw that after each click the browser uses more memory. If I comment the getAjaxPage(); row in the "success" section the situation starts to get better, but of course I lose all the internal navigation.

What could I do to avoid this problem?

Many thanks to all!

Upvotes: 0

Views: 473

Answers (1)

Shadow Wizard
Shadow Wizard

Reputation: 66388

Every call to $('a.ajaxc').click() is adding new event handler thus every click causes more requests to be made. After the first click, every click will cause two requests. Another click? Another three requests. Etc.

Put the handler outside the function and you will have only one AJAX call per click:

$(document).ready(function() {
    $('a.ajaxc').click(getAjaxPage);
});

I also don't see the reason behind calling getAjaxPage again from within the callback, so remove it as well to avoid infinite loop of requests.

Upvotes: 2

Related Questions