Home  >  Article  >  Web Front-end  >  How to bury the front end? A brief analysis of the method of using vue custom instructions to bury front-end points

How to bury the front end? A brief analysis of the method of using vue custom instructions to bury front-end points

青灯夜游
青灯夜游forward
2022-07-14 20:44:024981browse

How to bury front-end points? The following article will introduce to you how to implement front-end burying points through Vue custom instructions. I hope it will be helpful to everyone!

How to bury the front end? A brief analysis of the method of using vue custom instructions to bury front-end points

(Learning video sharing: vue video tutorial)

In marketing activities, users’ preferences and preferences can be obtained by burying points. Interaction habits, thereby optimizing the process, further improving user experience and increasing conversion rate.

In the previous implementation of hidden points, hidden points were actively reported through events when specific buttons or pictures were clicked or exposed. This method is okay when there are relatively few buried points in the project. Once a large number of buried points are needed in the project, it is inevitable to add a lot of business code. It has also largely caused the high coupling between hidden logic and business logic.

In order to improve this situation, we have made some small improvements to the original point burying method, which has greatly improved the point burying efficiency.

Before elaborating on our buried point transformation, it is necessary to have a brief understanding of some common sense about buried points.

What are the ways to report hidden points?

You must know that there are many types of hidden points, and there are also various ways to report them. There are three common methods of burying points on the front end:

  • Manual burying
  • Visual burying
  • Traceless burying

Manual Buried points, as the name suggests, is to write code purely manually, call the functions provided by the buried point SDK, add corresponding methods in the business logic that needs to be buried, and report the buried point data. This is also the method that has been used before.

Visual buried points refer to configuring buried points through the visual system. Not many people are exposed to this method, so I won’t go into details.

Traceless burying, also called automatic burying and full burying. That is, intercept and bury all global events and page loading cycles.

What kind of data are generally buried?

In order to achieve data analysis and facilitate subsequent operations and product strategy adjustments, it is generally necessary to make statistics on the following points:

  • Page buried points: Statistics Information about users entering or leaving the page, such as the number of page views (PV), the number of people browsing the page (UV), the length of stay on the page, device information, etc.
  • Click Burial: Count the clicks triggered by users during the page browsing process Events, such as the number of clicks on buttons, navigation or pictures
  • Exposure buried points: statistics on whether specific elements have been effectively exposed

Requirement analysis

This article is based on the need to add buried points in recent projects. An ideal solution we need is:

  • Buried points should be separated from the business as much as possible, and the buried point logic should be independent of the business
  • Try not to intrude into the business code
  • Agree on the specifications and handle the buried logic through unified closing ports

Since the project is developed by Vue, Therefore, consider using custom instructions to complete hidden point reporting. The reason for choosing custom instructions is also because it can decouple the business and hidden points to a certain extent.

Page burying points have been removed for us at the framework level. The main concern here is click burying points and exposure burying points.

The implementation idea is actually very clear: mount special attributes on the DOM node that needs to be buried, and monitor and mount the events corresponding to the corresponding attributes through the buried point SDK , report buried point data when an event is triggered.

Then the question is, how to monitor?

For click events, we can use addEventListener to listen for click events. this is very simple.

It’s a little troublesome to expose elements.

First let’s take a look at why we need to monitor exposure:

How to bury the front end? A brief analysis of the method of using vue custom instructions to bury front-end points

In order to measure the user’s interest in the product, we need to calculate the click-through rate (number of clicks/ number of exposures). In order to ensure the accuracy of the click-through rate, we must ensure that users actually browse these products (for example, the machine wine product area at the bottom of the picture above, because users need to scroll the page, it is possible for users to see this area).

So how to determine whether an element appears in the visible area of ​​the page?

Follow the past practice: listen to the scroll event, calculate the position of the monitoring area and the window through the getBoundingClientRect() method, and then determine whether the element appears in the visible area of ​​the page. However, due to the frequent triggering of scroll events, performance problems are huge.

Based on this, the browser specially created an Intersection ObserverAPI for us, which handles all performance-related details and allows developers to only care about business logic:

How to bury the front end? A brief analysis of the method of using vue custom instructions to bury front-end points

Due to the uncertainty of users browsing pages, repeated exposure behavior must be avoided. After this is exposed, just remove it for observation.

Code Implementation

The above requirements analysis is still relatively abstract. Let’s take a look at the final implementation based on the code.

Click class encapsulation

The processing of click events is relatively simple. Each click triggers data reporting:

// src/directives/track/click.js
import { sendUBT } from "../../utils/ctrip"

export default class Click {
  add(entry) {
    // console.log("entry", entry);
    const traceVal = entry.el.attributes["track-params"].value
    const traceKey = entry.el.attributes["trace-key"].value
    const { clickAction, detail } = JSON.parse(traceVal)
    const data = {
      action: clickAction,
      detail,
    }
    entry.el.addEventListener("click", function() {
      console.log("上报点击埋点", JSON.parse(traceVal))
      console.log("埋点key", traceKey)
      sendUBT(traceKey, data)
    })
  }
}

Exposure class Encapsulation

exposure is relatively complicated.

First instantiate a global _observer through new IntersectionObserver(). If you get effective exposure (here, the element will be exposed when more than half of the elements appear), then get it trace-key (buried key) and track-params (buried value) on the DOM node.

// src/directives/track/exposure.js
import "intersection-observer"
import { sendUBT } from "../../utils/ctrip"

// 节流时间调整,默认100ms
IntersectionObserver.prototype["THROTTLE_TIMEOUT"] = 300

export default class Exposure {
  constructor() {
    this._observer = null
    this.init()
  }

  init() {
    const self = this

    // 实例化监听
    this._observer = new IntersectionObserver(
      function(entries, observer) {
        entries.forEach((entry) => {
          // 出现在视窗内
          if (entry.isIntersecting) {
            // 获取参数
            // console.log("埋点节点", entry.target.attributes);
            const traceKey = entry.target.attributes["trace-key"].value
            const traceVal = entry.target.attributes["track-params"].value
            console.log("traceKey", traceKey)
            console.log("traceVal", traceVal)

            const { exposureAction, detail } = JSON.parse(traceVal)
            const data = {
              action: exposureAction,
              detail,
            }

            // 曝光之后取消观察
            self._observer.unobserve(entry.target)

              self.track(traceKey, data)
          }
        })
      },
      {
        root: null,
        rootMargin: "0px",
        threshold: 0.5, // 元素出现面积,0 - 1,这里当元素出现一半以上则进行曝光
      }
    )
  }

  /**
   * 元素添加监听
   *
   * @param {*} entry
   * @memberof Exposure
   */
  add(entry) {
    this._observer && this._observer.observe(entry.el)
  }

  /**
   * 埋点上报
   *
   * @memberof Exposure
   */
  track(traceKey, traceVal) {
    // console.log("曝光埋点", traceKey, JSON.parse(traceVal));
    sendUBT(traceKey, traceVal)
  }

}

Instruction Encapsulation

With the click and exposure classes, the next step is to encapsulate the Vue instructions, which is also the core of the reason why semi-automatic burying can be achieved.

There is a scenario here where for the same button or picture, there is a scenario where both the hidden point needs to be clicked and the hidden point needs to be exposed. Therefore, the design of the command supports the scenarios of separate incoming and simultaneous incoming:

  • v-track:click|exposure
  • ##v -track:exposure
  • // src/directives/track/index.js
    import Vue from "vue"
    import Click from "./click"
    import Exposure from "./exposure"
    
    // 实例化曝光和点击
    const exp = new Exposure()
    const cli = new Click()
    
    Vue.directive("track", {
      bind(el, binding) {
        // 获取指令参数
        const { arg } = binding
        arg.split("|").forEach((item) => {
          // 点击
          if (item === "click") {
            cli.add({ el })
          } else if (item === "exposure") {
            exp.add({ el })
          }
        })
      },
    })
also needs to be introduced in

src/index.js:

import "./directives/track"

Use

It is also very simple to use where you need to bury the point:

<img
  ref="imageDom"
  trace-key="o_img"
  v-track:click|exposure
  :track-params="
    JSON.stringify({
      exposureAction: &#39;s_pictures&#39;,
      clickAction: &#39;c_pictures&#39;,
      detail: {
        value: &#39;测试&#39;,
      },
    })
  "
/>

is not enough

One of the custom instructions through

Vue With simple encapsulation, the business code and the hidden code are decoupled to a certain extent. Compared with before, both the development cost and maintenance cost of the buried code have been reduced a lot.

But this is only the simplest implementation. There are many situations that need to be considered:

    The frequency of exposure is very high. Can batch reporting be considered?
  • A user visits half of the page, suddenly cuts out, and then re-enters. How should I report this situation?
  • If the user device does not support
  • Intersection ObserverAPI, should we consider backward compatibility?
In view of the fact that this burying plan is still being improved, we will wait for subsequent improvements and smooth operation in the business. I will share the details with you.

[Related video tutorial recommendations:

vuejs entry tutorial, web front-end entry]

The above is the detailed content of How to bury the front end? A brief analysis of the method of using vue custom instructions to bury front-end points. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete