Code Injection Optimization
Optimizing code injection in mini-programs can be approached from two perspectives: optimizing code volume and optimizing execution time.
1. Avoid Multiple Reads and Writes During Startup
getStorage
and setStorage
should only be used for persistent data storage and not for runtime data transfer or global state management. Excessive reading and writing of storage during startup will significantly impact the time it takes to inject code into the mini-program.
For simple data sharing, you can use a global data object added to the App
:
// app.js
App({
globalData: {
// Global shared data
userName: 'transsion',
},
});
// pages/index.js
const app = getApp();
Page({
onLoad() {
const { userName } = app.globalData;
},
});
2. Avoid Complex Computations During Startup
During mini-program initialization (outside of Page
and App
definitions) and in the relevant startup lifecycles, avoid executing complex computational logic. Complex computations will also block the current JavaScript thread, affecting startup time. It is recommended to defer complex computations until after startup is complete.