JS 中这些冷门但好用的 API,你知道多少?

数字化管理平台
Vue3+Vite+VueRouter+Pinia+Axios+ElementPlus
Vue权限系统案例
个人博客地址

  1. Intl.DateTimeFormat

    Intl.DateTimeFormat 对象能使日期和时间在特定的语言环境下格式化。

    // 创建一个新的 Intl.DateTimeFormat 对象
    Intl.DateTimeFormat()
    
    // getter 函数,根据此 DateTimeFormat 对象的区域设置和格式化选项格式化日期
    Intl.DateTimeFormat.prototype.format()
    

    示例:

    // 实例化一个日期对象
    const date = new Date()
    // 创建一个新的 Intl.DateTimeFormat 对象
    let dtf_en = new Intl.DateTimeFormat('en-US').format(date)
    // 使用 locales 参数指定美式英语 (US English):month-day-year 格式
    console.log(dtf_en) // 5/6/2023
    // 使用 locales 参数指定中文 (CH Chinese):month-day-year 格式
    let dtf_ch = new Intl.DateTimeFormat('zh-CH').format(date)
    console.log(dtf_ch) // 2023/5/6
    // 请求参数 (options) 中包含参数星期 (weekday),并且该参数的值为长类型 (long) - 参考语言环境对应输出
    let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }
    let dtf_ch_options = new Intl.DateTimeFormat('zh-CH', options).format(date)
    console.log(dtf_ch_options); // 2023年5月6日星期六
    

    API 参考地址:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

  2. Navigator.sendBeacon

    navigator.sendBeacon(url, data) 方法可用于通过 HTTP POST 将少量数据 异步 传输到 Web 服务器。

    • data 参数是将要发送的 ArrayBufferArrayBufferViewBlobDOMStringFormDataURLSearchParams 类型的数据。

    • 当用户代理成功把数据加入传输队列时,sendBeacon() 方法将会返回 true,否则返回 false

    • 方法主要用于满足统计和诊断代码的需要。在项目中可做"埋点"处理,收集用户的使用习惯和信息数据。

    可以解决传统方式(如下)出现的问题(迫使用户代理延迟卸载文档)

    • 发起一个同步 XMLHttpRequest 来发送数据。
    • 创建一个 img 元素并设置 src,大部分用户代理会延迟卸载(unload)文档以加载图像。

    navigator.sendBeacon 优势

    • 相较于img标签,使用navigator.sendBeacon会更规范,数据传输上可传输资源类型会更多。

    • 对于ajax在页面卸载时上报,ajax有可能没上报完,页面就卸载了导致请求中断,因此ajax处理这种情况时必须作为同步操作.

    • sendBeacon是异步的,不会影响当前页到下一个页面的跳转速度,且不受同域限制。这个方法还是异步发出请求,但是请求与当前页面脱离关联,作为浏览器的任务,因此可以保证会把数据发出去,不拖延卸载流程。

    在会话结束时发送统计数据

    网站通常希望在用户完成页面浏览后向服务器发送分析或诊断数据,最可靠的方法是在 visibilitychange 事件发生时发送数据

    document.addEventListener('visibilitychange', function logData() {
      if (document.visibilityState === 'hidden') {
        navigator.sendBeacon('/log', analyticsData);
      }
    });
    

    基于Navigator.sendBeacon的埋点上报

    Navigator.sendBeacon是目前通用的埋点上报方案,Navigator.sendBeacon方法接受两个参数,第一个参数是目标服务器的 URL,第二个参数是所要发送的数据(可选),可以是任意类型(字符串、表单对象、二进制对象等等)。

    • 页面停留时间上报埋点

      绑定点击事件,当点击目标元素时,触发埋点上报。

      function clickButton(url, data) {
          navigator.sendBeacon(url, data)
      }
      
    • 页面停留时间上报埋点

      路由文件中,初始化一个startTime,当页面离开时通过路由守卫计算停留时间。

      let url = ''// 上报地址
      let startTime = Date.now()
      let currentTime = ''
      router.beforeEach((to, from, next) => { 
           if (to) {
               currentTime = Date.now()
               stayTime = parseInt(currentTime - startTime)
               navigator.sendBeacon(url, {time: stayTime})
               startTime = Date.now()
           }
      })
      
    • 内容可见埋点

      通过交叉观察器去监听当前元素是否出现在页面

      // 可见性发生变化后的回调 
      function callback(data) { 
          navigator.sendBeacon(url, { target: data[0].target, text: '内容可见' }) 
      } 
      // 交叉观察器配置项 
      let options = {}; 
      // 生成交叉观察器 
      const observer = new IntersectionObserver(callback); 
      // 获取目标节点 
      let target = document.getElementById("target"); 
      // 监听目标元素 
      observer.observe(target);
      

猜你喜欢

转载自blog.csdn.net/qq_39335404/article/details/130641121
今日推荐