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
462 views
in Technique[技术] by (71.8m points)

javascript - Can I prevent history.popstate from triggering on initial page-load?

I'm working on a site that serves content via AJAX.

If you click an item in the menu, a content div gets updated with $.get response, nothing fancy.

I'm implementing history.pushState to allow navigation with the browser's back/forward button.

I have the following to load content on history navigation:

$(function() {
    $(window).bind("popstate", function() {
        $.getScript(location.href); 
    });
});

The problem is, when a page is loaded for the first time, this function does $.getScript so the page is loaded immediately again. The first time the page is loaded it renders the initial HTML view, then on the second load it renders the JS view, since its a JS request.

How could I prevent this event from firing on pages with HTML requests?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using the native HTML5 History API you're going to run into some problems, every HTML5 browser handles the API a little bit differently so you can't just code it once and expect it to work without implementing workarounds. History.js provides a cross-browser API for the HTML5 History API and a optional hashchange fallback for HTML4 browsers if you want to go down that route.

For upgrading your website into a RIA/Ajax-Application you can use this code snippet: https://github.com/browserstate/ajaxify

Which is part of the longer article Intelligent State Handling which goes into explanations about hashbang, hashes and the html5 history api.

Let me know if you need any further help :) Cheers.


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

...