evantianx / Bloooooooog

Place to record what I thought and learned
0 stars 0 forks source link

Web Beacon API #95

Open evantianx opened 5 years ago

evantianx commented 5 years ago

The Beacon API is used for sending small amounts of data to a server without waiting for a response.

为什么不用 Ajax ?

Ajax 发出请求后会等待服务器响应,当网络堵塞时,响应时间会很长。举例来说,如果需要在页面卸载的时候发送一些用户数据,使用 Beacon API 要优于 Ajax,因为前者不必等待服务器响应,只关心是否发出数据。

evantianx commented 5 years ago

Getting Started

// 返回值为 true 时,表示已经加入浏览器请求队列;反之则为失败
let result = navigator.sendBeacon(url, data)

navigator.sendBeacon(url, data) 需要传递两个参数:

Case

获取用户页面停留时长:

let startTime;
window.addEventListener('load', () => {
   startTime = performance.now(); 
})
window.addEventListener('beforeUnload', logVisit)

function logVisit() {
  if(!navigator.sendBeacon) return true;

  const url = '/api/log-visit';
  const data = new FormData();

  data.append('start', startTime);
  data.append('end', performance.now());
  data.append('url', document.url);

  navigator.sendBeacon(url, data);
}