语法
在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("navigate", (event) => { })
onnavigate = (event) => { }
事件类型
一个 NavigateEvent。继承自 Event。
示例
使用 intercept() 处理导航
js
navigation.addEventListener("navigate", (event) => {
// Exit early if this navigation shouldn't be intercepted,
// e.g. if the navigation is cross-origin, or a download request
if (shouldNotIntercept(event)) {
return;
}
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
// The URL has already changed, so show a placeholder while
// fetching the new content, such as a spinner or loading page
renderArticlePagePlaceholder();
// Fetch the new content and display when ready
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
},
});
}
});
注意: 在 Navigation API 可用之前,要实现类似的功能,您必须监听链接上的所有 click 事件,运行 event.preventDefault(),执行相应的 History.pushState() 调用,然后根据新的 URL 设置页面视图。而且这不会处理所有导航 — 只会处理用户发起的链接点击。
使用 scroll() 处理滚动
在这个拦截导航的例子中,handler() 函数首先获取并渲染一些文章内容,然后获取并渲染一些次要内容。一旦主要文章内容可用,立即将页面滚动到该内容是有意义的,以便用户可以与之交互,而不是等到次要内容也渲染完成。为了实现这一点,我们在两者之间添加了一个 scroll() 调用。
js
navigation.addEventListener("navigate", (event) => {
if (shouldNotIntercept(navigateEvent)) {
return;
}
const url = new URL(event.destination.url);
if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);
event.scroll();
const secondaryContent = await getSecondaryContent(url.pathname);
addSecondaryContent(secondaryContent);
},
});
}
});
规范
| 规范 |
|---|
| HTML # event-navigate |
浏览器兼容性
加载中…