Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Window: fetchLater() method

Limited availability

Experimental:This is anexperimental technology
Check theBrowser compatibility table carefully before using this in production.

ThefetchLater() method of theWindow interface creates a deferred fetch.

AfetchLater() request is sent once the page is navigated away from (it is destroyed or enters thebfcache), or after a providedactivateAfter timeout — whichever comes first.

ThefetchLater() methods returns aFetchLaterResult object containing a singleactivated value stating whether the request has been sent yet. Note the method does not return the result of the actual fetch when that happens (since it is often sent after the document has been destroyed) and the whole response of the fetch, including body and headers, is ignored.

Requests whose body is aReadableStream cannot be deferred.

ThefetchLater() method is controlled by theconnect-srcContent Security Policy directive rather than the directive of the retrieved resources.

Syntax

js
fetchLater(resource)fetchLater(resource, options)

Parameters

ThefetchLater() method takes all the same parameters asfetch(), but with one additionalactivateAfter option.

resource

This defines the resource that you wish to fetch. Identical tofetch(), this can either be:

  • A string or any other object with astringifier — including aURL object — that provides the URL of the resource you want to fetch. The URL may be relative to the base URL, which is the document'sbaseURI in a window context.
  • ARequest object.
optionsOptional

ADeferredRequestInit object containing any custom settings that you want to apply to the request, including anactivateAfter timeout value that defines how long the result should be deferred for before sending.

Exceptions

Thesame exceptions forfetch() can be raised forfetchLater(), along with the following additional exceptions:

QuotaExceededErrorDOMException

Use of this feature was blocked due to exceeding the available quota. SeefetchLater() quotas for more details. Callers offetchLater() should be defensive and catchQuotaExceededError errors in almost all cases, especially if they are embedding third-party JavaScript.

RangeErrorDOMException

Thrown when a negativeactivateAfter value is specified.

TypeErrorDOMException

In addition to the reasons forfetch(), this exception will also be thrown for aReadableStream request (which cannot be deferred) or for use of untrustworthy URLs (such ashttp://).

Return value

AFetchLaterResult containing anactivated boolean property indicating if the request has been sent yet.

Note:Once the fetch request is sent, its response — including the body and headers — is not made available and will be ignored.

Examples

ThefetchLater() quotas article provides examples of how the quotas are applied.

Defer aGET request until the page is navigated away from or closed

js
fetchLater("/send_beacon");

Defer aPOST request for around one minute

In this example we create aRequest, and provide anactivateAfter value to delay sending the request for 60,000 milliseconds (or one minute):

js
fetchLater("/send_beacon", {  method: "POST",  body: getBeaconData(),  activateAfter: 60000, // 1 minute});

Note:The actual sending time is unknown, as the browser may wait for a longer or shorter period of time, for example to optimize batching of deferred fetches.

Defer aPOST request for around one minute with a try/catch

The same example as above, but the best practice is to enclose this in a try/catch:

js
try {  fetchLater("/send_beacon", {    method: "POST",    body: getBeaconData(),    activateAfter: 60000, // 1 minute  });} catch (e) {  if (e instanceof QuotaExceededError) {    // Handle the quota error  } else {    // Handle other errors  }}

Defer aPOST request for around one minute and create a function to check if sent

js
const result = fetchLater("https://report.example.com", {  method: "POST",  body: JSON.stringify(myReport),  activateAfter: 60000 /* 1 minute */,});function checkIfFetched() {  return result.activated;}

Update a pending request

In this example we use anAbortController to cancel and recreate the request:

js
let beaconResult = null;let beaconAbort = null;function updateBeacon(data) {  const pending = !beaconResult || !beaconResult.activated;  if (pending && beaconAbort) {    beaconAbort.abort();  }  createBeacon(data);}function createBeacon(data) {  if (beaconResult && !beaconResult.activated) {    // Avoid creating duplicated beacon if the previous one is still pending.    return;  }  beaconAbort = new AbortController();  beaconResult = fetchLater({    url: data,    signal: beaconAbort.signal,  });}

Invalid examples

Any of the following calls tofetchLater() would throw:

js
// Only potentially trustworthy URLs are supportedfetchLater("http://untrusted.example.com");// The length of the deferred request has to be knownfetchLater("https://origin.example.com", { body: someDynamicStream });// Deferred fetching only works on active windowsconst detachedWindow = iframe.contentWindow;iframe.remove();detachedWindow.fetchLater("https://origin.example.com");

Specifications

No specification found

No specification data found forapi.Window.fetchLater.
Check for problems with this page or contribute a missingspec_url tomdn/browser-compat-data. Also make sure the specification is included inw3c/browser-specs.

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp