所以我正在尝试在HTML5历史API的帮助下异步加载内容。
我遇到的问题是,当点击<a href>
时,loadContent()
方法会被多次调用,特别是在跳过多个页面时。
当你跳过链接时,这会使页面变慢,而且它也会让我遇到一些不应该被加载多次的文件。
这是我现在正在使用的代码。
if (Modernizr.history) {
$(document).on("click", "a", function (event) {
event.preventDefault();
_href = $(this).attr("href");
history.pushState(null, null, _href);
loadContent("body", _href);
});
} else {
console.log("Browser does not support HTML5 History API. Please upgrade to a newer browser version.");
}
$(window).on("popstate", function () {
var link = location.pathname.replace(/^.*[\\/]/, ""); // get filename only
loadContent("body", link);
});
和loadContent()
方法:
function loadContent(divId, href) {
$(divId).load(href);
console.log("Loading: " + href);
};
我做错了什么想法? 如果您需要更多解释,请告诉我。
感谢您的关注!
答案 0 :(得分:0)
可能原因是当你的锚元素被点击时,你的代码
history.pushState(null, null, _href);
更新浏览器历史记录,后者又调度在当前处理程序执行完毕后调用的“popstate”事件。这就是为什么你会有
loadContent();
被叫两次。