我可以阻止history.popstate在初始页面加载时触发吗? [英] Can I prevent history.popstate from triggering on initial page-load?

查看:307
本文介绍了我可以阻止history.popstate在初始页面加载时触发吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个通过AJAX提供内容的网站。

I'm working on a site that serves content via AJAX.

如果点击菜单中的某个项目,内容div会以<$ c $更新c> $。得到回复,没什么特别的。

If you click an item in the menu, a content div gets updated with $.get response, nothing fancy.

我正在实施 history.pushState 允许使用浏览器的后退/前进按钮进行导航。

I'm implementing history.pushState to allow navigation with the browser's back/forward button.

我有以下内容在历史导航中加载内容:

I have the following to load content on history navigation:

$(function() {
    $(window).bind("popstate", function() {
        $.getScript(location.href); 
    });
});

问题是,当第一次加载页面时,此函数会 $。getScript 以便再次立即加载页面。第一次加载页面时,它会呈现初始HTML视图,然后在第二次加载时呈现JS视图,因为它是一个JS请求。

The problem is, when a page is loaded for the first time, this function does $.getScript so the page is loaded immediately again. The first time the page is loaded it renders the initial HTML view, then on the second load it renders the JS view, since its a JS request.

我怎样才能防止在使用HTML请求的页面上触发此事件?

How could I prevent this event from firing on pages with HTML requests?

推荐答案

使用本机HTML5历史记录API,您将遇到一些问题,每个HTML5浏览器处理API的方式略有不同,因此您不能只编写一次代码并期望它能够在不实现变通方法的情况下工作。 History.js 为HTML5 History API和可选的 hashchange提供了跨浏览器的API HTML4浏览器的回退如果你想沿着那条路走下去。

Using the native HTML5 History API you're going to run into some problems, every HTML5 browser handles the API a little bit differently so you can't just code it once and expect it to work without implementing workarounds. History.js provides a cross-browser API for the HTML5 History API and a optional hashchange fallback for HTML4 browsers if you want to go down that route.

要将你的网站升级为RIA / Ajax-Application,你可以使用这段代码片段:
https://github.com/browserstate/ajaxify

For upgrading your website into a RIA/Ajax-Application you can use this code snippet: https://github.com/browserstate/ajaxify

这是较长文章智能状态处理的一部分,该文章将对此进行解释。 hashbang,哈希和html5历史api。

Which is part of the longer article Intelligent State Handling which goes into explanations about hashbang, hashes and the html5 history api.

如果您需要任何进一步的帮助,请告诉我:)干杯。

Let me know if you need any further help :) Cheers.

这篇关于我可以阻止history.popstate在初始页面加载时触发吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆