statechange load is causing multiple loads of the same page
Asked Answered
T

1

7

It appears that this line in the statechange event:

$('#content').load(State.data.home_page);

...is causing the same page to load multiple times which is resulting in glitches on my site. What can I do to fix this?

enter image description here

(function($) {

    function loadHome() {
        $('#content').load(site.url + '/ #primary', function() {
            $(this).fadeIn(50);
        });
    }

    // User event
    $('.site-title a').on('click', function(e) {
        e.preventDefault();

        var newData = { home_page: site.url + '/ #primary' };
        History.pushState(newData, site.title, site.url);
        loadHome();
    });

    // History event
    History.Adapter.bind(window, 'statechange', function(){
        var State = History.getState();
        $('#content').load(State.data.home_page);
    });

})(jQuery);

Update

Ok, so I learned that .pushState actually calls statechange.

So basically, I'm thinking this is what's happening:

  • User clicks on .site-title a
  • pushState() is called which calls statechange which loads the part of the page.
  • At the same time, loadHome() is also called which loads the same.

I can see that is why I am getting multiple instances of the same page. I thought statechange is only called when the user clicks the back button on the browser. That kind of clears things up, but I'm still at a loss as to how to move forward with this. I'm not sure what to replace that .load line with in the statechange event, assuming that's the culprit.

Trump answered 31/1, 2015 at 2:35 Comment(2)
you are binding an event handler inside another event handler. Every time you click a link, will add it againTrauner
@Trauner Thanks, I fixed that. However, I have another problem now. I updated my post with it.Trump
N
1

When you click the link the following happens, in order:

  1. You push new state onto the stack
  2. The state change event fires
  3. The event initiates a load of data.home_page
  4. loadHome is called
  5. loadHome initiates a load

As you can see, steps 3 and 5 are redundant.

Can you instead bind to the popstate event?

Nucleus answered 9/2, 2015 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.