小程序冷启动,热启动时间
验收的时候要看冷启动,热启动时间,豆包给的答案,先记录一下,不确定生效不生效,这个是兼容低版本库的,在为程序后台查看数据
App({
onLaunch() {
this.globalData.isColdStart = true
this.globalData.startTs = Date.now()
this.globalData.enableHighPrecision = false
this.globalData.perfInstance = null
if (wx.canIUse('getPerformance')) {
const perf = wx.getPerformance()
if (typeof perf.mark === 'function') {
perf.mark('boot_start')
this.globalData.perfInstance = perf
this.globalData.enableHighPrecision = true
}
}
// 这里放你原本所有onLaunch业务代码
},
onShow() {
// 这里放你原本所有onShow业务代码
let costMs = 0
if (this.globalData.enableHighPrecision && this.globalData.perfInstance) {
const perf = this.globalData.perfInstance
perf.mark('boot_end')
perf.measure('boot_total_cost', 'boot_start', 'boot_end')
const entryList = perf.getEntriesByName('boot_total_cost')
costMs = Math.round(entryList[0].duration)
} else {
costMs = Date.now() - this.globalData.startTs
}
if (wx.canIUse('reportPerformance')) {
const metricId = this.globalData.isColdStart ? 1001 : 1002
wx.reportPerformance(metricId, costMs)
}
this.globalData.isColdStart = false
},
globalData: {
isColdStart: false,
startTs: 0,
enableHighPrecision: false,
perfInstance: null
}
})
这个是最开始的版本,但是版本库不一样,会报错TypeError: perf.mark is not a function
App({
onLaunch() {
// 1. 先打计时起点(最顶部)
this.globalData.isColdStart = true;
const perf = wx.getPerformance();
perf.mark('boot_start');
this.globalData.perfInstance = perf;
// 2. 你的原有业务逻辑
console.log('执行登录、全局初始化');
},
onShow() {
// 1. 先执行你所有onShow业务代码
console.log('刷新数据、页面更新逻辑');
// 2. 全部执行完,最后上报性能耗时(最底部)
const perf = this.globalData.perfInstance;
if (!perf) return;
perf.mark('boot_end');
perf.measure('boot_total_time', 'boot_start', 'boot_end');
const measureList = perf.getEntriesByName('boot_total_time');
const costTime = Math.round(measureList[0].duration);
wx.reportPerformance(this.globalData.isColdStart ? 1001 : 1002, costTime);
this.globalData.isColdStart = false;
},
globalData: {
isColdStart: false,
perfInstance: null
}
})
浙公网安备 33010602011771号