小程序检测元素首次出现在可视区域上报埋点遇到的问题 createIntersectionObserver

背景

有一个商品的介绍页面,按照头图+内容的样式排列,头图高度不固定,内容高度不固定,检测到用户可以看到内容部分的时候进行一次上报。

遇到的问题:

1、加了检测元素出现在可视区域的方法不生效

2、解决了不生效的问题之后,发现头图大加载慢的时候,内容部分会先加载一闪而过,用户其实没看到内容,但是检测的结果是内容出现到了可视区域

3、切换页面,卸载observer不生效

环境

使用的框架:vue2+taro3

解决办法

问题1:检测方法必须写到onReady方法里面,等页面加载完毕

问题2:加个定时器,500ms之后再加载

问题3:必须在onUnload方法里面卸载

完整代码

最后赋上代码

js 复制代码
<script>
import Taro from '@tarojs/taro'
export default {
  data () {
    return {
      observer: null, // 监听元素是否进入可视区域
      timer: null
    }
  },
  onReady () {
  // 记录食谱内容是否曝光
    this.timer = setTimeout(() => {
      this.queryElement()
      clearTimeout(this.timer)
      this.timer = null
    }, 500)
  },
  onUnload () {
    this.disconnectObserver()
  },
  methods: {
    /**
     * @description 停止观察并销毁 observer 实例
     */
    disconnectObserver () {
      if (this.observer) {
        this.observer.disconnect()
        this.observer = null
      }
    },
    /**
     * @description 检测元素是否加载
     */
    queryElement () {
      Taro.createSelectorQuery().select('.recipe-detail-info__card').boundingClientRect().exec((res) => {
        if (res && res[0]) {
          this.setupObserver()
        } else {
          console.error('Element not found.')
        }
      })
    },
    /**
     * @description 检测元素是否出现在可视区域
     */
    setupObserver () {
      this.observer = Taro.createIntersectionObserver()
      this.observer.relativeToViewport({
        bottom: -100
      }).observe('.recipe-detail-info__card', (res) => {
        if (res.intersectionRatio > 0) {
          // 上报埋点
          this.disconnectObserver()  //这里加是因为只想首次上报,如果实时上报可以不清除
        }
      })
    }
  }
}
</script>
相关推荐
Freedom风间3 小时前
前端优秀编码技巧
前端·javascript·代码规范
努力成为包租婆3 小时前
微信小程序 van-dropdown-menu
微信·微信小程序·小程序
萌萌哒草头将军3 小时前
🚀🚀🚀 Openapi:全栈开发神器,0代码写后端!
前端·javascript·next.js
萌萌哒草头将军3 小时前
🚀🚀🚀 Prisma 爱之初体验:一款非常棒的 ORM 工具库
前端·javascript·orm
拉不动的猪4 小时前
SDK与API简单对比
前端·javascript·面试
runnerdancer4 小时前
微信小程序蓝牙通信开发之分包传输通信协议开发
前端
山海上的风4 小时前
Vue里面elementUi-aside 和el-main不垂直排列
前端·vue.js·elementui
电商api接口开发4 小时前
ASP.NET MVC 入门指南二
前端·c#·html·mvc
亭台烟雨中4 小时前
【前端记事】关于electron的入门使用
前端·javascript·electron