Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

statechange load is causing multiple loads of the same page

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.

like image 563
J82 Avatar asked Jan 31 '15 02:01

J82


1 Answers

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?

  • https://html.spec.whatwg.org/#handler-window-onpopstate
  • https://developer.mozilla.org/en-US/docs/WindowEventHandlers.onpopstate
like image 76
error Avatar answered Nov 02 '22 21:11

error