我已经阅读了所有有关于history.js的stack overflow帖子包括这篇,这篇和这篇,并查看了源代码,但作为一个新手的JavaScript / jQuery,我很难弄明白如何实际实现以支持html 5历史记录,并回退到支持html4浏览器,例如ie8/9。我可以理解从尽可能呈现一致的URL中获得的UX效益,以及如何解决深度链接并允许书签,我想要实施,但当我尝试在我的网站上实际使用时,我感到有些迷失。
将history.js脚本添加到我的页面后
需要修改的代码是:
function(window,undefined){
// Prepare
var History = window.History; // Note: We are using a capital H instead of a lower h
if ( !History.enabled ) {
// History.js is disabled for this browser.
// This is because we can optionally choose to support HTML4 browsers or not.
return false;
}
// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
var State = History.getState(); // Note: We are using History.getState() instead of event.state
History.log(State.data, State.title, State.url);
});
// Change our States
History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1"
History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2"
History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3"
History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4"
History.back(); // logs {state:3}, "State 3", "?state=3"
History.back(); // logs {state:1}, "State 1", "?state=1"
History.back(); // logs {}, "Home Page", "?"
History.go(2); // logs {state:3}, "State 3", "?state=3"
})(window);
如果这段代码只是提供历史控制的示例,那么//Change our states
是所有新代码都要放置的地方吗?
还是说我应该替换整个代码块并编写自己的代码呢(考虑到我的编程新手身份,我使用jquery来帮助我)。
我正在阅读这篇关于动态内容加载的文章,并尝试将其实现在我的网站上(我可以让这段代码运行,但我知道它在ie8/9上不会很好),但我无法弄清楚如何与history.js结合使用。
此外,我还想了解history.js如何与modernizr配合使用?
它是modernizr.history的替代品(进行测试,如果不支持.js,则返回典型页面加载),还是会像这样运行:
if (Modernizr.history) {
//Code goes here that works if it's HTML 5 Browser with .history support? I know some HTML5 browsers deal with .history oddly (read buggy) so what happens in those cases?
} else {
//code from above goes here? with function(window, undefined){...etc... ?
}