Skip to main content




Reduce delayed navigations


Updated

Es común que una página o aplicación tenga análisis u otros datos sin enviar en el momento en que un Username la cierra. Para evitar la pérdida de datos, algunos sitios utilizan una llamada sincrónica para XMLHttpRequest () para mantener la página o aplicación abierta hasta que sus datos se pasen al server. No solo existen mejores formas de guardar datos, sino que esta técnica crea una mala user experience al retrasar el cierre de la página hasta varios segundos.

Esta práctica debe cambiar y los browsers están respondiendo. los XMLHttpRequest ()
the specification is already scheduled for disapproval and removal. Chrome 80 takes the first step by not allowing synchronous calls within various event handlers, specifically beforeunload, unload, pagehideand visibilitychange when they are fired on layoff. WebKit also recently landed a commitment that implements the same behavior change.

In this article, I will briefly describe the options for those who need time to update their sites and describe the alternatives for XMLHttpRequest ().

Temporary exclusions

Chrome doesn't just want to disconnect XMLHttpRequest (), which is why some opt-out options are available. For sites on the Internet, a proof of origin is available. Con esto, agrega un token específico de origen a los headers de su página que habilita la sincronización XMLHttpRequest () calls. This option ends shortly before the launch of Chrome 89, sometime in March 2021. Enterprise Chrome customers can also use AllowSyncXHRInPageDismissal policy flag, which ends at the same time.

Alternatives

Regardless of how you send the data to the server, it is best to avoid waiting for the page to download to send all the data at once. In addition to creating a bad user experience, you risk losing data if something goes wrong. Download events often not activated on mobile browsers
because there many ways to close una pestaña o browser en sistemas operativos móviles sin la unload event de disparo. Con
XMLHttpRequest (), using small payloads was a choice. Now it is a requirement. Both alternatives have a 64 KB upload limit per context, as required by the spec.

Get keepalive

the Get API
provides a robust means of handling interactions with the server and a consistent interface para su uso en diferentes API de plataforma. Entre sus opciones esta keepalive, which ensures that a request continues regardless of whether the page that made it remains open or not:

window.addEventListener('unload', {
fetch('/siteAnalytics', {
method: 'POST',
body: getStatistics(),
keepalive: true
});
}

the fetch () The method has the advantage of more control over what is sent to the server. What I don't show in the example is that fetch () also returns a promise that is resolved with a Response object. Since I am trying to prevent the page from downloading, I chose not to do anything with it.

SendBeacon ()

SendBeacon ()

it actually uses the Fetch API under the hood, which is why it has the same 64KB payload limitation and why it also ensures that a request continues after a page download. Its main advantage is its simplicity. It allows you to submit your data with a single line of code:

window.addEventListener('unload', {
navigator.sendBeacon('/siteAnalytics', getStatistics());
}

conclusion

With the greater availability of
fetch ()

in browsers, XMLHttpRequest () Con suerte, se eliminará de la plataforma Web en algún momento. Los proveedores de navegadores están de acuerdo en que debería eliminarse, pero llevará tiempo. Dejar de lado uno de sus peores casos de uso es un primer paso que mejora la experiencia del usuario para todos.

Photo by Matthew hamilton in Unsplash