Understanding the JavaScript Runtime and Application Lifecycle in Mini-Programs
Execution Environment Overview
The core runtime relies on JavaScript, functioning as a bridge that processes data for the UI layer and captures user interactions. To streamline development, the framework extends stendard JavaScript with dedicated registration methods (App and Page), global access utilities (getApp and getCurrentPages), and proprietary capabilities such as authentication and payment processing. Each script operates within an isolated scope, supporting modular architecture. Because the environment lacks a traditional DOM or window object, web-specific APIs are unavailable. The compiled script bundle runs continuously from launch until termination, functioning similarly to a background service worker, commonly referred to as the Application Service.
Application Initialization and State Management
The core entry point uses a configuration object passed to the App constructor. This object defines lifecyccle callbacks and shared state. The framework distinguishes between active (foreground) and suspended (background) states. Minimizing the application or switching away places it in the background rather than immediately terminating it. Resuming brings it back to the foreground. Actual termination occurs only after prolonged background inactivity or under system memory pressure.
App({
globalData: {
serviceTitle: 'CorePlatform'
},
onLaunch: function(context) {
// Initialize core dependencies and validate environment
},
onShow: function(context) {
// Handle foreground activation and refresh data
},
onHide: function() {
// Clean up temporary resources or pause timers
},
onError: function(trace) {
console.error('System fault detected:', trace);
}
});
The onLaunch and onShow callbacks recieve context objects containing navigation metadata. Depending on the entry point, thesee payloads may include referrerInfo.appId, which identifies the source application when navigating via cross-program links or specific external channels.
Global Instance Access
The getApp() function retrieves the singleton application object, enabling access to shared configurations across modules.
// utils/runtime.js
const runtime = getApp();
console.log(runtime.globalData.serviceTitle); // Outputs 'CorePlatform'
Implementation Constraints
- The
App()declaration must appear exactly once in the root entry script. Duplicate registrations are prohibited. - Avoid invoking
getApp()within methods defined inside theAppconfiguration; reference the instance directly viathis. - Do not query the navigation stack using
getCurrentPages()duringonLaunch, as the initial view has not yet mounted. - Never manually trigger lifecycle methods after obtaining the instance through
getApp(). - The
getCurrentPages()utility returns a array representing the active page stack, with each element containing the correspondingPageinstance.