我使用了pace.js
,但pace
的问题是,加载动画是在页面完全加载后才显示的。
所以,我尝试并制定了一个解决方案,onclick页面上的每个链接,jquery抓取并停止从浏览器直接到链接的事件,并向该链接发送一个ajax get请求。加载页面时,它会在当前页面上显示动画。页面完全加载后,它会用接收到的数据替换整个当前文档,并替换地址栏中的页面 url。
<script type="text/javascript">
$( document ).ready(function() {
$('a').click(function() {
var dt;
if (/#/.test(this.href)) {
return true;
}else{
document.getElementById("before-loader").style.display= "block";//show loading animation
var that = this;
$.ajax({
type: "GET",
url: that.href,
success: function(response){
document.open();
document.write(response);
document.title = response.pageTitle;
window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", that.href);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";//hide loading animation
}
});
return false;
}
});
});
</script>
问题在于单击浏览器后退按钮时,地址栏中的 URL 发生了变化,但页面内容仍然保持不变。 我该如何克服这个问题?
更新
se0kjun
的答案没有解决我的问题(我希望它在复制/粘贴提供的代码后起作用),但让我找到了正确的方向。经过一些研究和重写流程后,它可以工作,但我仍然很困惑为什么它可以工作。
$( document ).ready(function() {
$('a').click(function() {
if (/#/.test(this.href)) {
return true;
}else{
window.history.pushState(null, 'Production Workflow & Sales Management', this.href);
loadContent(this.href);
return false;
}
});
});
function loadContent(href) {
document.getElementById("before-loader").style.display= "block";
$.ajax({
type: "GET",
url: href,
success: function(response){
document.open();
document.title = response.pageTitle;
document.write(response);
document.close();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown);
document.getElementById("before-loader").style.display= "none";
}
});
}
window.onpopstate = function(event) {
link = location.pathname.replace(/^.*[\\/]/, ""); // get filename only
loadContent(link);
};
也许我应该多学习。
最佳答案
我认为您想要 popstate
事件。
当您单击链接时,ajax 会向 that.href
发出请求。之后,如果请求成功,您将收到响应并调用 pushstate
。
当您单击后退按钮时,会触发 popstate
事件。您可以在 popstate
事件处理程序中加载上一页。
以下是popstate
的使用示例
window.onpopstate = function(event) {
//you add a path in pushstate
$('.container').load(event.state.path);
alert('popstate');
};
这是一个fiddle
关于javascript - 通过js设置页面历史记录和页面内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37107190/