内容加载/历史API的问题

问题描述 投票:0回答:1

所以我正在尝试在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);
};

我做错了什么想法?如果您需要更多解释,请告诉我。

感谢您的关注!

javascript jquery html html5 asynchronous
1个回答
0
投票

可能原因是当你的锚元素被点击时,你的代码

history.pushState(null, null, _href);

更新浏览器历史记录,进而调度在当前处理程序执行完毕后调用的“popstate”事件。这就是为什么你会有 loadContent(); 被叫两次。

© www.soinside.com 2019 - 2024. All rights reserved.