大网数据广告活动
Web 标准与前端开发

Document: prerenderingchange event

· 52CE 我爱测

The **`prerenderingchange`** event is fired on a prerendered document when it is activated (i.e., the user views the page).

Speculation Rules API

The prerenderingchange event is fired on a prerendered document when it is activated (i.e., the user views the page).

Syntax

Use the event name in EventTarget/addEventListener:

addEventListener("prerenderingchange", (event) => { })

Alternatively, assign to the event handler property of the interface:

onprerenderingchange = (event) => { }

Event type

A generic Event.

Examples

Preventing code from running during prerendering

The example shows how to defer code, that would otherwise run during prerendering, until after page activation. This is useful for deferring analytics code, which is only relevant when and if the page is actually viewed.

The code checks if prerendering is running using Document.prerendering, and if so adds an event listener to run an analytics initialization function once the page is activated. On a page that is not prerendering the analytics code is run immediately.

if (document.prerendering) {
  document.addEventListener("prerenderingchange", initAnalytics, {
    once: true,
  });
} else {
  initAnalytics();
}

Note that this kind of code should not be used for measuring how often a prerender is activated, because the code may run after a prerendered page has already activated.

[!NOTE] See the Speculation Rules API landing page and particularly the Unsafe speculative loading conditions section for more information on the kinds of activities you might wish to delay until after prerendering has finished.

Measuring prerendering activations

This code shows how to measure how often a prerender is activated. It uses the prerenderingchange to track activation events, and Performance.getEntriesByType() to track navigation activations.

if (document.prerendering) {
  document.addEventListener(
    "prerenderingchange",
    () => {
      console.log("Prerender activated after this script ran");
    },
    { once: true },
  );
} else if (performance.getEntriesByType("navigation")[0]?.activationStart > 0) {
  console.log("Prerender activated before this script ran");
} else {
  console.log("This page load was not via prerendering");
}

Specifications

Browser compatibility

See also

  • Speculation Rules API
  • Document.prerendering property
  • PerformanceNavigationTiming.activationStart property

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。