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.

J82
  • 7,605
  • 21
  • 48
  • 79
  • 2
    you are binding an event handler inside another event handler. Every time you click a link, will add it again – charlietfl Jan 31 '15 at 02:56
  • @charlietfl Thanks, I fixed that. However, I have another problem now. I updated my post with it. – J82 Jan 31 '15 at 14:52

1 Answers1

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?

error
  • 658
  • 4
  • 14