本文为前端统计的Demo。实现了一个前端统计的SDK。之后会更新在更多前端性能的文章在专栏。
前端统计的范围
- 访问量 PV
- 自定义事件(如统计一个按钮被点击了多少次)
- 性能数据
- 页面各种类型报错
const PV_URL_SET = new Set()
class Statistic{
constructor(projectId){
this.productId = projectId;
this.initPerformance() // 性能统计
this.initError() // 错误监控
}
// 发送统计数据
send(url,params = {}){
params.productId = productId;
const paramsArr = [];
for(let key in params) {
const val = params[key];
paramsArr.push(`${key}=${value}`)
}
const newUrl = `${url}?{paramArr.join('$')}`
// 用 <img> 发送:1. 可跨域;2. 兼容性非常好
// Navigator.sendBeacon() 也是可行方案
const img = document.createElement('img')
img.src = newUrl //自动发送get请求
}
// 初始化性能统计
initPerformance(){
const url ="";
this.send(url,performance.timing)
// 给最原始的、完整的结果,原始数据
}
pv(){
const href = location.href;
if (PV_URL_SET.get(href)) return // 不重复发送 pv
this.event('pv')
PV_URL_SET.add(href)
}
event(key, val) {
const url = '' // 自定义事件统计 server API
this.send(url, {key, val})
}
// 初始化错误监控
initError(){
window.addEventListener('error',event =>{
const { error, lineno, colno } = event
this.error(error, { lineno, colno })
})
// Promise 未 catch 住的报错
window.addEventListener('unhandledrejection',
event => {
this.error(new Error(event.reason),
type:'unhandledrejection' })
})
}
error(err,info = {}){
const url = "";
const {message,stack} = err;
this.send(url,{message,stack,..info})
}
}