Bin*_*min 31 ajax jquery browser-history
我想以跨浏览器的方式使用jQuery和AJAX实现导航历史记录.我的方法是使用window.history.pushState并回退到/#!/url不支持的浏览器中的哈希URL window.history.pushState.
例如:
<a href="/home">home</a>
<a href="/about">about</a>
<a href="/contact">contact</a>
Run Code Online (Sandbox Code Playgroud)
在支持的浏览器window.history.pushState,点击这些链接之一,应该没有刷新页面更改地址http://domain.com/home,http://domain.com/about等.当浏览器不支持window.history.pushState,就应该使用片段标识符,即:http://domain.com/#!/ home,http://domain.com/#!/about.
更新:根据这里的反馈,我实现了Ajax SEO(git),它使用
旧的浏览器回退的HTML5历史API的jQuery地址/#!/url.
Ben*_*Lee 22
// Assuming the path is retreived and stored in a variable 'path'
if (typeof(window.history.pushState) == 'function') {
window.history.pushState(null, path, path);
} else {
window.location.hash = '#!' + path;
}
Run Code Online (Sandbox Code Playgroud)
我一直在使用回退哈希网址的东西:
History = History || {};
History.pathname = null;
History.previousHash = null;
History.hashCheckInterval = -1;
History.stack = [];
History.initialize = function () {
if (History.supportsHistoryPushState()) {
History.pathname = document.location.pathname;
$(window).bind("popstate", History.onHistoryChanged);
} else {
History.hashCheckInterval = setInterval(History.onCheckHash, 200);
}
};
History.supportsHistoryPushState = function () {
return ("pushState" in window.history) && window.history.pushState !== null;
};
History.onCheckHash = function () {
if (document.location.hash !== History.previousHash) {
History.navigateToPath(document.location.hash.slice(1));
History.previousHash = document.location.hash;
}
};
History.pushState = function (url) {
if (History.supportsHistoryPushState()) {
window.history.pushState("", "", url);
} else {
History.previousHash = url;
document.location.hash = url;
}
History.stack.push(url);
};
History.onHistoryChanged = function (event) {
if (History.supportsHistoryPushState()) {
if(History.pathname != document.location.pathname){
History.pathname = null;
History.navigateToPath(document.location.pathname);
}
}
};
History.navigateToPath = function(pathname) {
History.pushState(pathname);
// DO SOME HANDLING OF YOUR PATH HERE
};
Run Code Online (Sandbox Code Playgroud)
您可以使用以下命令将点击事件绑定到此:
$(function(){
$("a").click(function(){
var href = $(this).attr('href');
History.navigateToPath( href )
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
如果您需要对此示例进行更多解释,我将很高兴听到它.
编辑
请看我的其他答案.
| 归档时间: |
|
| 查看次数: |
28710 次 |
| 最近记录: |