Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

javascript - onpopstate handler - ajax back button

I'm using pushState to create meaningful urls for ajax content on my site. I want to refresh the ajax content when the user hits the forward or back buttons. I'm having problems however as chrome (correctly) impliments onpopstate on both 'history traversal' (forward/back buttons) and 'the end' (page load). I'd like to create an onpopstate handler that differentiates between page load and history traversal, as I don't want to refresh my ajax content if it's already just been loaded successfully. Can anybody help me with differentiating between the two?

window.onpopstate = function (event) {
    // If : Forward/back button pressed
        // Reload any ajax content with new variables
    // Else : Page load complete
        // Do nothing - content already loaded and correct
}

See http://code.google.com/p/chromium/issues/detail?id=63040 for more details on chrome and onpopstate.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way would be to initialize a variable to false on page load, and then on your popstate event, check that variable. If it's still false, set it to true and do nothing. From then on all of your other popstate events should be only from back/forward events.

var loaded = false;

window.onpopstate = function(e) {
    if (!loaded) {
        loaded = true;
        return;
    } else {
        // run your stuff...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...