Search code examples
javascriptjqueryajaxreloadstack

JS seems to stay in DOM on Ajax reloaded pages


OK this is an odd error, as it's the first ajax page without any complete reloads I'm creating it's an error I never had to face before... and even the Internet doesn't help me - as it doesn't seem to be an usual problem.

Let's get to the Problem step by step: I have a page where the Ajax request is triggered by a function which simplified looks like this:

$("a[rel='tab']").live('click',function(e) {

pageurl = $(this).attr('href');
$.ajax({url:pageurl+'?rel=tab',success: function(data){
  $('#content').html(data);
}});
if(pageurl!=window.location){
  window.history.pushState({path:pageurl},'',pageurl);
}
e.preventDefault();
return false;
});

This is parsed by the PHP File and if the property is set the design won't be loaded but instead just the file itself gets loaded - easy hu?

OK, now the problem itself - it was obvious that the page became slower with the time but I didn't really bother at first as I thought it was some mistake in the designs javascripts - but it wasn't.

So I took a look at the firebug and what I've seen explained a lot -> The Requests stack up with every new page! Of course that would lead into an overkill... Well at first I thought it were just the "setInterval"'s and got a workaround running which resets them on each reload.

But that wasn't the only case they also seem to stack up in "scripts" as I don't think that's a plain history as just the reloaded scripts show up more than once!

Any hints in the right would be really helpfull as I am pretty much stuck here!


Solution

  • OK as it seems the issue is just related to the setInterval after all - After trying around for a while I came to the conclusion that this was the main problem, and it was just some kind of a loop in firebug itself.

    However maybe someone gets stuck on the same issue so the solution is pretty much this way: You have to: 1. Create an array where to store your Intervals 2. call your setIntervals this way 3. Reset them on each "new window"

    var intervalArr = new Array();
    
    function killIntervals(){
    while(intervalArr.length > 0)
        clearInterval(intervalArr.pop());
    };
    

    These are the array and the function

    So these should be added in your AJAX Request function:

    killIntervals();
    intervalArr.push(setInterval (yourintervalfunction, 5000));
    

    I hope this will come in handy for someone.