开发者

What is the recommended ordering of an AJAX load and history.pushState?

For instance, in jQuery, setting up a link to load something into a region, should I load the content before calling history.pushState?

$('#link').click(function () {
    $('#region').load('regionContent', function () {
        history.pushState(null, null, 'newUrl');
    });
    return false;
});

Or should I load the content after calling history.pushState?

$('#link').click(function () {
    history.pushState(null, null, 'newUrl');
    $('#region').load('regionContent');
    return false;
});

The former seems preferable to me, because I feel the URL shouldn't change until the content does, but I've seen the latter more often (e.g. https://github.com/blog/760-the-tree-slider), so I'm wondering whic开发者_运维百科h is considered best practice.


With both your examples, when the user hits the back button the content isn't going to change! As you haven't got anything inside your state change handler.

Essentially you'll want to do this:

$('#link').click(function () {
    History.pushState(null,null,'newUrl');
});
$('body').bind('statechange',function(){
    $('#content').load(History.getState().url);
});

This will make it when you click a link, the state of your page will change, and that given the state of your page has changed, it will load in the new content. Hitting the back button in your browser, will also cause the state to change, and thus load in your new content.

Now here I have used History.js's statechange and History.getState().url instead of the native popstate and State.url as different browsers will fire the state change event at different times. For instance safari will the state change event at page load, where chrome and firefox don't - causing in safari your content to load twice. History.js provides a consistent API across all browsers, and if you wish even HTML4 browsers by falling back to hashes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜