Séb*_*uel 3 javascript ajax html5 browser-history pushstate
我做了一个单页的网站.当用户单击菜单按钮时,内容将加载ajax.它工作正常.为了改善SEO并允许用户复制/过去不同内容的URL,我使用
function show_content() {
// change URL in browser bar)
window.history.pushState("", "Content", "/content.php");
// ajax
$content.load("ajax/content.php?id="+id);
}
Run Code Online (Sandbox Code Playgroud)
它工作正常.URL更改,浏览器不会重新加载页面
但是,当用户单击浏览器中的后退按钮时,URL将更改并且必须加载内容.
我做到了这一点,它的工作原理:
window.onpopstate = function(event) {
if (document.location.pathname == '/4-content.php') {
show_content_1();
}
else if (document.location.pathname == '/1-content.php') {
show_content_2();
}
else if (document.location.pathname == '/6-content.php') {
show_content_();
}
};
Run Code Online (Sandbox Code Playgroud)
你知道是否有办法改进这段代码?
Tim*_*len 10
我所做的是将对象文字传递给pushState()页面加载.这样,您始终可以返回到第一个创建的pushState.在我的情况下,我必须先推两次才能回去.在页面加载上推送状态帮助了我.
HTML5允许您使用数据属性,因此对于您的触发器,您可以使用它们来绑定HTML数据.
我使用try catch,因为我没有时间为旧浏览器找到polyfill.如果您的情况需要,可能需要检查Modernizr.
页面加载
try {
window.history.pushState({
url: '',
id: this.content.data("id"), // html data-id
label: this.content.data("label") // html data-label
}, "just content or your label variable", window.location.href);
} catch (e) {
console.log(e);
}
Run Code Online (Sandbox Code Playgroud)
事件处理者
填充默认信息的对象
var obj = {
url: settings.assetsPath, // this came from php
lang: settings.language, // this came from php
historyData: {}
};
Run Code Online (Sandbox Code Playgroud)
绑定history.pushState()触发器.在我的情况下是一个委托,因为我在页面上有动态元素.
// click a trigger -> push state
this.root.on("click", ".cssSelector", function (ev) {
var path = [],
urlChunk = document.location.pathname; // to follow your example
// some data-attributes you need? like id or label
// override obj.historyData
obj.historyData.id = $(ev.currentTarget).data("id");
// create a relative path for security reasons
path.push("..", obj.lang, label, urlChunk);
path = path.join("/");
// attempt to push a state
try {
window.history.pushState(obj.historyData, label, path);
this.back.fadeIn();
this.showContent(obj.historyData.id);
} catch (e) {
console.log(e);
}
});
Run Code Online (Sandbox Code Playgroud)
将history.back()事件绑定到自定义按钮,链接或其他内容.我使用,.preventDefault()因为我的按钮是一个链接.
// click back arrow -> history
this.back.on("click", function (ev) {
ev.preventDefault();
window.history.back();
});
Run Code Online (Sandbox Code Playgroud)
当历史记录弹出时 - >检查推送状态,除非它是第一次尝试
$(window).on("popstate", function (ev) {
var originalState = ev.originalEvent.state || obj.historyData;
if (!originalState) {
// no history, hide the back button or something
this.back.fadeOut();
return;
} else {
// do something
this.showContent(obj.historyData.id);
}
});
Run Code Online (Sandbox Code Playgroud)
使用对象文字作为参数可以很方便地传递你的id.然后你可以使用一个功能showContent(id).
无论我在哪里使用this它,只不过是一个存储在IIFE中的jQuery对象/函数.
请注意我将这些脚本放在我的实现中,并结合您初始请求中的一些想法.所以希望这给你一些新的想法;)
| 归档时间: |
|
| 查看次数: |
8900 次 |
| 最近记录: |