小程序检测元素首次出现在可视区域上报埋点遇到的问题 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>
相关推荐
晷龙烬1 分钟前
Vue 3 自定义指令:从“瑞士军刀”到“专属工具” !
前端·javascript·vue.js
MediaTea3 分钟前
思考与练习(第四章 程序组成与输入输出)
java·linux·服务器·前端·javascript
BD_Marathon4 分钟前
【JavaWeb】NPM_简介和相关配置
前端·npm·node.js
2501_915106325 分钟前
用 HBuilder 上架 iOS 应用时如何管理Bundle ID、证书与描述文件
android·ios·小程序·https·uni-app·iphone·webview
咸鱼加辣7 分钟前
【前端框架】react
前端·react.js·前端框架
unicrom_深圳市由你创科技8 分钟前
Vue 3 高效开发技巧总结
前端·javascript·vue.js
HIT_Weston10 分钟前
66、【Ubuntu】【Gitlab】拉出内网 Web 服务:Gitlab 配置审视(十)
前端·ubuntu·gitlab
长空任鸟飞_阿康14 分钟前
LangChain 技术栈全解析:从模型编排到 RAG 实战
前端·python·langchain
2501_9159090614 分钟前
资源文件混淆在 iOS 应用安全中的实际价值
android·安全·ios·小程序·uni-app·iphone·webview
2501_9159184114 分钟前
iOS App 性能测试中常被忽略的运行期问题
android·ios·小程序·https·uni-app·iphone·webview