Small program on-demand dynamic loading and subpackaging method based on uniform subpackaging mode
By adopting a unified sub-package model for mini-programs, the dynamic loading of sub-packages on demand is achieved, which solves the problems of dynamic loading mechanism and resource management in mini-programs, realizes efficient sub-package loading and resource utilization, and improves startup performance and user experience.
Patent Information
- Application Number
- CN202511644652.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-11
- Publication Date
- 2026-02-03
- Estimated Expiration
- 2045-11-11
AI Technical Summary
The existing mini-program sub-package loading mechanism lacks dynamic capabilities, resulting in low resource utilization efficiency, high development and maintenance costs, and problems such as circular dependencies or repeated resource loading.
The method of dynamically loading sub-packages on demand in mini programs is based on a unified sub-package model. It achieves efficient dynamic loading and unified management of sub-packages through standardized configuration information, sub-package lifecycle management and dependency graph construction. This includes initializing standardized configuration information, building a sub-package lifecycle state machine and a directed acyclic dependency graph, establishing a sub-package runtime manager, and performing on-demand loading and page rendering.
It enables precise management and on-demand loading of mini-program subpackage resources, reduces initial loading size and time cost, improves startup performance and user experience, increases system resource utilization and reduces memory usage.
Smart Images

Figure CN121455562A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to mobile application development technology, and more particularly to a method for dynamically loading sub-packages on demand in mini-programs based on a unified sub-package model. Background Technology
[0002] As the functionality of mini-programs continues to expand, their code size also increases, leading to longer initial launch times and a degraded user experience. In current mini-program development practices, sub-package loading technology is widely used, but existing sub-package loading mechanisms still have some problems that urgently need to be addressed: Sub-package specifications and interfaces differ across platforms, requiring developers to write adaptation code for different platforms, increasing development and maintenance costs. Existing sub-package loading mechanisms generally lack dynamism; once the sub-package structure is determined, it is difficult to dynamically adjust it according to the actual operating environment and user needs, resulting in low resource utilization efficiency. Managing dependencies between sub-packages is complex; developers need to manually maintain dependencies between sub-packages, which can easily lead to circular dependencies or duplicate resource loading, affecting application performance and user experience.
[0003] To overcome the above-mentioned shortcomings, there is an urgent need for a method for dynamic loading of mini-program sub-packages on demand based on a unified sub-package model. This method can achieve efficient dynamic loading and unified management of mini-program sub-packages through standardized configuration information, sub-package resource lists, sub-package lifecycle management, and dependency graph construction. Summary of the Invention
[0004] This invention provides a method for dynamically loading subpackages on demand in mini-programs based on a unified subpackage model, which can solve the problems in the prior art.
[0005] A first aspect of this invention provides a method for dynamically loading sub-packages on demand in a mini-program based on a unified sub-package model, comprising:
[0006] Initialize standardized configuration information for the unified subpackage mode, including subpackage structure template, subpackage interface specification, subpackage status definition, and subpackage lifecycle rules; and establish a subpackage resource list based on the subpackage structure template, including a code file list, a style file list, a static resource file list, and inter-subpackage dependency declarations.
[0007] A subpackage lifecycle state machine is constructed based on the subpackage state definition to realize subpackage lifecycle management based on state transition rules and system resource status;
[0008] Based on the target page path information and the sub-package resource list, a directed acyclic sub-package dependency graph is constructed, and the target sub-package node and its predecessor dependency node are determined by the graph traversal algorithm.
[0009] Establish a subpackage runtime manager, including a unified interface layer for providing standardized subpackage operation interfaces, a lifecycle management layer for managing subpackage status, and a resource scheduling layer for implementing resource scheduling;
[0010] The subpackage loading process is executed through the subpackage runtime manager, which loads the target subpackage on demand and renders the page.
[0011] In one alternative implementation,
[0012] The process of generating the standardized configuration information includes:
[0013] Multi-level configuration verification is performed during the configuration initialization phase, including a static verification layer that verifies structural integrity, type consistency, value range constraints, and reference integrity, as well as a semantic verification layer that verifies subpackage dependency relationships, interface specification consistency, and lifecycle rule conflict detection.
[0014] Adaptive configuration optimization includes: building a performance monitoring and feedback mechanism based on a sliding time window mechanism to collect and analyze in real time the sub-packet loading time, memory usage trend, CPU utilization, network throughput, interaction response latency, resource usage, and page access frequency in the recent access sequence to evaluate the system's operating status; adaptively adjusting lifecycle rule thresholds, component hierarchy priority, scheduling strategy parameters, and memory reclamation thresholds based on the system operating status evaluation results, wherein the scheduling strategy parameters are used to control the dynamic adjustment of the thread pool capacity in the resource scheduling layer, the component hierarchy priority is used to guide the component hierarchy division of the target sub-packet, and the adjustment range of each parameter is limited to a preset range through parameter boundary verification; incremental rollback mechanism and canary release strategy are used for configuration updates, and when any performance indicator deviates from the target range for more than a preset time, the configuration parameters are rolled back to the previous stable version.
[0015] In one alternative implementation,
[0016] Based on the subpackage structure template, a subpackage resource list is created, including a list of code files, a list of style files, a list of static resource files, and inter-subpackage dependency declarations, including:
[0017] A four-layer structure is adopted to organize the subpackage resources, including the code file layer, style file layer, static resource layer and dependency declaration layer; a subpackage resource list is established based on the four-layer structure, and resource scanning is performed on each layer to generate a set of code files, a set of style files and a set of static resource files;
[0018] By scanning the code reference statements in the code file set, the style reference statements in the style file set, and the resource inline references in the static resource file set, dependency reference information between sub-packages is collected, and a dependency declaration set containing source sub-package identifier, target sub-package identifier, and dependency weight is generated based on the dependency reference information.
[0019] Extract the path, size, hash value, and type attribute information of each resource file in the subpackage resource list, and determine the resource file attributes used for subpackage loading priority sorting based on the weighted calculation results of real-time access frequency, dependency reference count in the dependency declaration set, and file size according to the preset weighting coefficient;
[0020] An incremental update mechanism is established. By monitoring changes to subpackaged resources and calculating changes in the hash values of resource files, the dependency reference information in the dependency declaration set is updated, and the priority attributes of resource files in the subpackaged resource list are recalculated based on the updated dependency reference information.
[0021] In one alternative implementation,
[0022] Constructing a sub-package lifecycle state machine based on the aforementioned sub-package state definition includes:
[0023] The state machine includes six states: pending loading, loading, loaded, activated, frozen, and pending release, and sets state transition trigger conditions and transition rules. The state machine sets different state transition strategies according to component type. Basic components remain stable after entering the activated state, business components are converted to the frozen state when switching pages, and extended components are given priority to enter the frozen state. The state machine obtains the system memory usage in real time through the memory monitoring module. When the memory usage exceeds the preset threshold, it automatically converts the least used loaded sub-packages to the frozen state and releases the memory resources they occupy.
[0024] In one alternative implementation,
[0025] Based on the target page path information and the sub-package resource list, a directed acyclic sub-package dependency graph is constructed. The target sub-package node and its predecessor dependency nodes are determined by a graph traversal algorithm, including:
[0026] Based on the target page path information, obtain the initial set of subpackage nodes that have a direct reference relationship with the target page from the subpackage resource list; starting from the initial set of subpackage nodes, recursively construct the subpackage dependency graph based on the dependency declaration set, and use the source subpackage identifier and target subpackage identifier in the dependency declaration set as the source node and target node of the dependency graph, respectively, and the dependency weight as the weight attribute of the connecting edge, wherein the direction of the directed edge is the dependency pointing to the dependent;
[0027] A depth-first traversal is performed on the sub-package dependency graph, recording the node access timestamp and earliest reachable timestamp during the traversal process. Cycles are identified, and the edge with the lowest dependency weight in the identified cycle is marked as an unnecessary dependency edge. After removing the unnecessary dependency edges, a breadth-first traversal algorithm is used to hierarchically mark the sub-package nodes, grouping sub-package nodes at the same level into the same set, and determining the set of preceding dependent nodes for each sub-package node. The access order of the nodes is the loading priority order of the sub-packages.
[0028] In one alternative implementation,
[0029] Resource scheduling includes:
[0030] The resource scheduling layer includes a multi-level parallel scheduling system, with a first scheduler for scheduling code files, a second scheduler for scheduling style files, and a third scheduler for scheduling static resource files. Each scheduler includes an independent task queue and a dynamically expandable and shrinkable thread pool. The capacity of the thread pool is dynamically adjusted according to the current CPU utilization, memory utilization, and network status of the device. During the loading process, the execution status of tasks in each scheduler is monitored in real time. When an abnormal task execution is detected, an automatic retry mechanism is triggered. If the number of retries exceeds a preset threshold, the corresponding resource is switched to a locally preset degraded resource.
[0031] A distributed resource pool is constructed to support the multi-level parallel scheduling system. Packaged resources are stored in a code resource pool, a style resource pool, and a static resource pool, respectively, according to their type. The distributed resource pool adopts a fragmented storage mechanism, where each resource fragment includes resource content, resource feature values, and a resource reference count. When multiple packages are detected referencing the same resource, duplicate resources are identified through resource feature value matching, and only one copy of the resource is retained in the resource pool. Other packages reference this resource copy through a resource mapping table. The loading priority of the preceding dependent nodes is higher than that of the target package nodes.
[0032] In one alternative implementation,
[0033] The sub-package loading process, executed through the sub-package runtime manager, includes on-demand loading and page rendering of the target sub-package, including:
[0034] The component hierarchy is prioritized based on the priority attributes of resource files in the subpackage resource list. The target subpackage is divided into three levels: basic components, business components, and extended components. The basic components are used to build the DOM tree structure and implement user interaction functions, and are loaded synchronously with the page. The business components are used to implement data processing and functional operations, and are loaded when the page enters the visible area. The extended components are used to implement independent functional modules and are loaded when a user operation event is received. When the system memory usage exceeds a first preset threshold or the CPU usage exceeds a second preset threshold, the loading of the extended components is interrupted.
[0035] A layered rendering strategy is adopted. After the basic components are loaded, the page framework is rendered first. After the business components are loaded, the content of the visible area is rendered. For list-type data, virtual scrolling is used to optimize rendering performance. Extended components update the page content through asynchronous rendering mode, and the rendering task is split into several micro-tasks to be executed in time.
[0036] A second aspect of the present invention provides an electronic device, comprising:
[0037] processor;
[0038] Memory used to store processor-executable instructions;
[0039] The processor is configured to invoke instructions stored in the memory to execute the aforementioned method.
[0040] A third aspect of the present invention provides a computer-readable storage medium having stored thereon computer program instructions that, when executed by a processor, implement the aforementioned method.
[0041] This invention establishes a unified sub-package model and standardized configuration information, enabling precise management and on-demand loading of mini-program sub-package resources. This effectively reduces the initial loading size and time cost, and improves mini-program startup performance and user experience.
[0042] This invention introduces a sub-package lifecycle state machine and a dependency analysis mechanism based on graph algorithms, optimizes the sub-package loading strategy, realizes intelligent preloading and resource reuse, effectively improves system resource utilization and reduces memory consumption.
[0043] This invention designs a layered runtime manager that enhances the scalability and cross-platform adaptability of subpackage management through the collaborative work of a unified interface layer, a lifecycle management layer, and a resource scheduling layer, thereby reducing development difficulty and improving code maintainability. Attached Figure Description
[0044] Figure 1This is a flowchart illustrating the method for dynamically loading subpackages on demand in a mini-program based on a unified subpackage model, according to an embodiment of the present invention.
[0045] Figure 2 Flowchart for generating standardized configuration information;
[0046] Figure 3 A comparison chart showing the impact of different component loading strategies on page loading performance. Detailed Implementation
[0047] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments.
[0048] Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0049] The technical solution of the present invention will be described in detail below with reference to specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments.
[0050] Figure 1 This is a flowchart illustrating the on-demand dynamic loading of subpackages in a mini-program based on a unified subpackage model, as described in an embodiment of the present invention. Figure 1 As shown, the method includes:
[0051] Initialize standardized configuration information for the unified subcontracting mode. The standardized configuration information includes subcontracting structure templates, subcontracting status definitions, and subcontracting lifecycle rules to establish subcontracting organization specifications and operational constraint benchmarks.
[0052] Based on the sub-package organization hierarchy and dependency relationship specifications defined in the sub-package structure template, a sub-package resource list containing resource files and inter-sub-package dependency declarations is established. The sub-package resource list provides basic data support for subsequent dependency analysis and loading scheduling.
[0053] Using the state types and transition conditions in the sub-packet state definition, a sub-packet lifecycle state machine is constructed. The state machine implements sub-packet lifecycle management based on state transition rules and system resource status, and realizes dynamic release and reuse of memory resources through state control.
[0054] Based on the inter-package dependency declarations extracted from the sub-package resource list, a directed acyclic sub-package dependency graph is constructed in combination with the target page path information. The target sub-package node and its predecessor dependency node are determined by the graph traversal algorithm, and a sub-package loading sequence that satisfies the dependency order constraint is generated.
[0055] To execute the subpackage loading sequence and state machine control strategy, a subpackage runtime manager is established. The subpackage runtime manager includes a unified interface layer for providing standardized subpackage operation interfaces, a lifecycle management layer for calling the subpackage lifecycle state machine to implement state management, and a resource scheduling layer for executing resource download tasks in the subpackage loading sequence. The lifecycle management layer triggers the loading and unloading operations of the resource scheduling layer through the state transition rules of the state machine.
[0056] After receiving the page navigation request by the unified interface layer, the subpackage runtime manager executes the subpackage loading process according to the subpackage loading sequence and the current state of the state machine. The resource scheduling layer loads the target subpackage and its predecessor dependent subpackages according to the priority order determined by the subpackage loading sequence. The lifecycle management layer controls the activation, freezing and unloading of each subpackage according to the transition rules of the state machine, so as to realize the on-demand loading of the target subpackage and page rendering.
[0057] For example, when the mini-program starts, it loads the configuration file and executes a multi-level configuration verification process. The static verification layer checks the integrity of the sub-package structure template, confirming that each sub-package configuration item contains three necessary fields: sub-package identifier, root path, and resource type list. It also verifies that the reference paths between sub-packages all point to the declared valid sub-package identifier. The semantic verification layer performs topological sorting detection on sub-package dependencies, identifies circular dependencies and records abnormal sub-package identifiers, and checks for state transition conflicts in lifecycle rules. For example, it verifies that the same sub-package will not be marked as both mandatory pre-loading and lazy loading simultaneously. After the configuration verification passes, the performance monitoring feedback mechanism is initialized, setting the sliding time window length to 300 seconds and collecting system performance data every 60 seconds, including four metrics: page load time, sub-package download time, peak memory usage, and CPU utilization. When the average page load time exceeds 2000 milliseconds or the peak memory usage exceeds 70% of the device's available memory within the last five sampling periods, the system automatically adjusts the component hierarchy priority, demoting some business components to extended components to delay their loading. Simultaneously, it increases the core thread count in the thread pool of the resource scheduling layer, with the adjustment range limited to 80% to 150% of the current value through parameter boundary checks. After the configuration parameters are adjusted, a canary release strategy is adopted, initially applying the new configuration to 10% of users and continuously monitoring for 120 seconds. If the page load failure rate increases by more than 5 percentage points or the percentage of user operation response delays exceeding 500 milliseconds increases by more than 3 percentage points, an incremental rollback mechanism is triggered, restoring the configuration parameters to the previous stable version.
[0058] The process of establishing the subpackage resource list is based on a multi-layered organizational structure, dividing each subpackage into four layers: page layer, component layer, utility layer, and style layer. The resource scanning module traverses the directories of each layer, identifying three file types: code files, style files, and static resource files, generating resource records containing three attributes: file path, file size, and file type. For page files scanned at the page layer, the system extracts component paths and API calls from their reference statements, recording the page files' dependencies on the component and utility layers. For component files in the component layer, its template references and script import statements are parsed to identify dependencies on other components, utility functions, and style files. For function library files in the utility layer, their module import statements are analyzed to record inter-utility dependencies. For style files in the style layer, their import statements and resource reference paths are detected to establish dependency mappings to static resources and other style files. After dependency scanning is complete, a dependency declaration set is generated. Each dependency declaration contains three fields: source subpackage identifier, target subpackage identifier, and dependency weight. The dependency weight is determined by the number of references; the weight increases by 1 for each reference. During the priority attribute calculation of resource files, the access frequency of each file over the past 30 days is obtained. The total number of times the file is referenced by other files from the dependency declaration set is counted as the dependency reference count. Simultaneously, the file size in bytes is read. The priority value is calculated using a weighted average: access frequency multiplied by a weight coefficient of 0.5, dependency reference count multiplied by a weight coefficient of 0.3, and the reciprocal of the file size multiplied by a weight coefficient of 0.2. The sum of these three weighted values is then normalized to a range of 0 to 100. A file monitoring mechanism is established to capture creation, modification, and deletion operations of resource files through file system event listeners. When a change in file content is detected, the SHA256 hash value of the file is calculated and compared with historical hash values. If the hash values differ, a dependency rescan is triggered, updating all dependency declarations related to that file and recalculating the priority attributes of the relevant files.
[0059] The subpackage lifecycle state machine defines six states: unloaded, loading, loaded, activated, frozen, and unloaded. A subpackage in the unloaded state transitions to the loading state upon receiving a loading trigger command. This transition occurs when the user navigates to a page containing the subpackage or when a preloading strategy is triggered. A subpackage in the loading state transitions to the loaded state after the resource files have been downloaded and the code registration is successful. A subpackage in the loaded state transitions to the activated state upon receiving an activation command, which originates from page rendering requirements or component instantiation requests. Activated subpackages execute different state preservation strategies based on their component type. Subpackages of basic component types remain activated after activation, ensuring the continued availability of framework components. Subpackages of business component types transition to the frozen state when a page switching event is triggered, releasing some memory resources but retaining code registration information. Subpackages of extended component types preferentially enter the frozen state after loading and are only activated when the user triggers a specific interaction event. The system memory monitoring module collects memory usage data every 3 seconds. When the memory usage rate exceeds 75%, the state machine automatically selects the least used activated subpackage and performs a freeze operation. The minimum usage criterion is the last access timestamp of the sub-packet. A timestamp queue of all activated sub-packets is maintained, sorted in ascending order of timestamp, with the sub-packets at the head of the queue being frozen first. A frozen sub-packet can be converted back to an activated state when its memory usage drops below 60% and a reactivation request is received. An activated or frozen sub-packet that has not been accessed for a long time and is experiencing system memory pressure is converted to an unloaded state. The unload operation clears all memory occupied by the sub-packet and removes it from the code registry.
[0060] The dependency graph construction process begins with the target page path information. The page path is parsed to obtain the subpackage identifier to which the page belongs. All page files and component files under that subpackage are searched in the subpackage resource list, and the subpackage identifiers referenced by these files are collected into an initial subpackage node set. Starting from the initial subpackage node set, the dependency declaration set is recursively queried. For each subpackage identifier in the set, all dependency declarations with that identifier as the source subpackage identifier are found. The target subpackage identifier is extracted and added to the processing queue, while the dependency weight is recorded as the edge weight attribute. The recursive query process continues until the processing queue is empty. The completed dependency graph is stored in the form of an adjacency list, with each node recording the subpackage identifier and a list of directed edges pointing to other nodes. A depth-first traversal algorithm performs cycle detection on the dependency graph. During the traversal, each node is marked with an access timestamp and an earliest reachable timestamp. The access timestamp records the sequence number of the first visit to the node, and the earliest reachable timestamp records the timestamp of the earliest visited node that can be reached from that node. When, during the traversal, it is found that the access timestamp of the target node of an edge is less than the access timestamp of the source node, and the earliest reachable timestamp of the target node is less than or equal to the access timestamp of the source node, the edge is determined to form a cycle. After identifying the cycle, all edges in the cycle are traversed, and the edge with the smallest dependency weight is marked as an unnecessary dependency edge and removed from the dependency graph. After the cycle is eliminated, a breadth-first traversal is performed for layer marking. All nodes with an in-degree of zero are marked as layer 0 and added to the queue. After a node is removed from the queue, the in-degree of all its successor nodes is decremented by 1. If the in-degree of a successor node becomes zero, it is marked as the next layer and added to the queue. The traversal process continues until the queue is empty. Sub-packet nodes at the same level are grouped into the same loading batch and can be loaded in parallel. The set of predecessor dependency nodes of each node is obtained by traversing the edge list in reverse, that is, collecting all source nodes pointing to that node. The level number of a node is the loading priority, and nodes with smaller level numbers are loaded first.
[0061] The resource scheduling layer comprises three independent schedulers: a code resource scheduler, a style resource scheduler, and a static resource scheduler. Each scheduler maintains a first-in-first-out (FIFO) task queue and a thread pool. The initial core thread count of the thread pool is 2, and the maximum thread count is determined by the number of CPU cores on the device. For single-core devices, the maximum thread count is 4; for dual-core and higher devices, the maximum thread count is twice the number of CPU cores. CPU utilization is monitored in real-time. When CPU utilization is below 40%, the core thread count of the thread pool increases by 1, but not exceeding the maximum thread count. When CPU utilization exceeds 80% and lasts for more than 5 seconds, the core thread count of the thread pool decreases by 1, but not falls below 1. Each task in the task queue contains four fields: resource URL, resource type, priority, and number of retries. The scheduler retrieves tasks from high to low priority and assigns them to idle threads for execution. A timeout of 8 seconds is set for each thread executing a download task. If the download fails, the task is re-added to the queue and the number of retries is increased. When the number of retries exceeds 3, the scheduler triggers a degradation mechanism, checking if a degraded resource with the same name exists in the local pre-built resource directory. If it exists, the degraded resource is used as a replacement; otherwise, a loading failure log is recorded and the resource is skipped. The distributed resource pool uses a fragmented storage strategy. The code resource pool stores JavaScript code files, the style resource pool stores CSS style files, and the static resource pool stores images and font files. Each resource fragment contains three fields: a byte array of resource data, a 32-bit integer of the resource characteristic value, and an integer of the resource reference count. The resource characteristic value is obtained by calculating the CRC32 checksum of the first 1024 bytes of the resource data. When multiple fragments reference the same resource, the scheduler calculates the resource characteristic value and searches for a match in the resource pool. If the characteristic values are the same, the complete data is compared to confirm resource consistency. After confirmation, the mapping relationship between the fragment identifier and the resource fragment index is recorded in the resource mapping table, and the resource reference count is incremented by 1. When a sub-package is unloaded, the resource reference count is decremented by 1. When the reference count drops to 0, the resource fragment is removed from the resource pool.
[0062] At the start of the sub-package loading process, resource files in the target sub-package are sorted and layered according to the resource file priority attributes in the sub-package resource list. Resource files with a priority value greater than 80 are classified as basic components, which typically include page framework components and core interaction components. Resource files with a priority value between 50 and 80 are classified as business components, including data display components and functional operation components. Resource files with a priority value less than 50 are classified as extended components, including statistical analysis components and auxiliary tool components. The loading tasks of basic components are submitted to the resource scheduling layer immediately upon page initialization, and the scheduler sets the priority of these tasks to the highest value of 100. The loading tasks of business components listen to the visible area of the page through the Intersection Observer. When the page scrolls to 300 pixels away from the expected rendering position of the business component, the loading task is submitted and the priority is set to 60. The loading tasks of extended components are bound to the user operation event listener. When the user clicks or touches to trigger the component expansion, the loading task is submitted and the priority is set to 30. The memory monitoring module continuously collects memory usage. When memory usage exceeds 70% or CPU usage exceeds 85%, the scheduler pauses the loading of extended components, and submitted extended component tasks are removed from the queue and marked as delayed. The rendering process employs a layered strategy. After the basic components are loaded, the rendering engine is invoked to construct the DOM tree skeleton structure, including page container nodes and navigation bar nodes, completing the initial screen frame rendering. After business components are loaded, the component type is determined. For list components, a virtual scrolling rendering mode is enabled, rendering only the list items within the visible area plus five buffer items before and after. The initial rendering quantity is calculated based on an estimated height of 150 pixels, and the rendering range is dynamically updated as the user scrolls. For form and card components, DOM node insertion and style application are performed directly. Extended components use an asynchronous rendering mode, breaking down the component's rendering task into four micro-tasks: creating a virtual DOM, calculating the layout, applying styles, and mounting the real DOM. These micro-tasks are scheduled and executed during browser idle time, with each micro-task taking no more than 16 milliseconds to avoid blocking the main thread.
[0063] For example, an e-commerce mini-program includes four sub-packages: Homepage, Product Details, Shopping Cart, and User Center. The Homepage sub-package is 180 kilobytes in size and contains three basic components: a carousel, a category navigation component, and a product recommendation list component, as well as one extended component: a coupon pop-up. The Product Details sub-package is 220 kilobytes in size and depends on the product card component from the Homepage sub-package. The Shopping Cart sub-package is 150 kilobytes in size and depends on the specification selector component from the Product Details sub-package. The User Center sub-package is 100 kilobytes in size and has no external dependencies. When a user enters the homepage from the application launch, the system parses the homepage path to obtain the Homepage sub-package identifier. A query in the dependency declaration set reveals that the Homepage sub-package has no prerequisite dependencies, so it is marked as level 0. The basic components of the Homepage sub-package include a carousel component (priority 85), a category navigation component (priority 82), a product recommendation list component (priority 78), and a coupon pop-up component (priority 45). The loading tasks for the carousel and category navigation are submitted. Two threads from the thread pool are allocated for parallel downloading. The carousel component download takes 120 milliseconds, and the category navigation component download takes 95 milliseconds. After downloading, the rendering engine builds the page framework, taking 50 milliseconds. The product recommendation list component starts loading when the page scrolls to 300 pixels from its rendering position, taking 180 milliseconds to download. After loading, the first 10 product items are rendered using virtual scrolling mode, each item with a height of 150 pixels, taking 80 milliseconds to render. When the user clicks on the coupon entry, the memory usage is detected to be 65%, meeting the loading condition. The coupon pop-up component loading task is submitted, taking 70 milliseconds to download. Asynchronous rendering is used, executing the task in four micro-tasks, for a total time of 60 milliseconds. When a user clicks on a product and enters its details page, the system parses the page path to obtain the product details subpackage identifier. A dependency declaration is then queried, revealing that the product details subpackage depends on the homepage subpackage. The homepage subpackage is already active, and the product details subpackage is marked as level 1. Loading the basic components of the product details subpackage begins, taking 280 milliseconds. Rendering the product image carousel and price information takes 110 milliseconds. When memory usage rises to 76%, the state machine converts the coupon pop-up component from the homepage subpackage to a frozen state, releasing approximately 15 kilobytes of memory, reducing memory usage to 74%.
[0064] In one alternative implementation,
[0065] The process of generating the standardized configuration information includes:
[0066] Multi-level configuration verification is performed during the configuration initialization phase, including a static verification layer that verifies structural integrity, type consistency, value range constraints, and reference integrity, as well as a semantic verification layer that verifies subpackage dependency relationships, interface specification consistency, and lifecycle rule conflict detection.
[0067] Adaptive configuration optimization includes: building a performance monitoring and feedback mechanism based on a sliding time window mechanism to collect and analyze in real time the sub-packet loading time, memory usage trend, CPU utilization, network throughput, interaction response latency, resource usage, and page access frequency in the recent access sequence to evaluate the system's operating status; adaptively adjusting lifecycle rule thresholds, component hierarchy priority, scheduling strategy parameters, and memory reclamation thresholds based on the system operating status evaluation results, wherein the scheduling strategy parameters are used to control the dynamic adjustment of the thread pool capacity in the resource scheduling layer, the component hierarchy priority is used to guide the component hierarchy division of the target sub-packet, and the adjustment range of each parameter is limited to a preset range through parameter boundary verification; incremental rollback mechanism and canary release strategy are used for configuration updates, and when any performance indicator deviates from the target range for more than a preset time, the configuration parameters are rolled back to the previous stable version.
[0068] For example, the standardized configuration information generation process mainly includes two stages: configuration initialization and verification, and adaptive optimization. Combined with... Figure 2 The standardized configuration information generation process is illustrated using a flowchart:
[0069] During the configuration initialization phase, the subpackage structure template defines the basic organizational form of the subpackages, including the boundary between the main package and subpackages, the internal file organization structure of the subpackages, and cross-subpackage referencing rules. The subpackage structure template uses a JSON format configuration file, with key fields including: packageType (values are "main" or "subpackage", indicating the package type), root (representing the subpackage root directory path), pages (an array containing all page paths within the subpackage), and independent (a boolean indicating whether it is an independent subpackage). The template may also include a preloadRule field to define the subpackage preloading rules, with a key-value pair structure where the key is the page path that triggers preloading, and the value is a list of preloaded packages and network conditions. The subpackage interface specification defines the standard interface for communication between subpackages, consisting of two parts: exported interface definitions and imported interface declarations. Exported interface definitions adopt a modular design pattern, declaring exposed methods, components, and data structures in package.json through the exports field. Imported interface declarations declare dependent external interfaces through the imports field. Each interface definition includes fields such as name (interface name), type (interface type, such as "function", "component", "data"), params (parameter list), and returnType (return value type).
[0070] The subpackage status definition describes the possible states and attributes of a subpackage during its lifecycle. In this embodiment, it includes six states: pending loading, loading, loaded, activated, frozen, and pending release. Each state has a corresponding resource occupancy level and transition conditions. The subpackage lifecycle rules define the triggering conditions and behaviors for subpackage status transitions. Rules are sorted by a priority field, with smaller values indicating higher priority. When multiple rules are triggered, they are executed according to priority.
[0071] In the configuration verification phase, static verification is performed first. Structural integrity verification ensures the configuration file contains all necessary fields, and missing or unnecessary fields are filled with default values. Type consistency verification checks if field types meet expectations; for example, `pages` must be an array type, and `independent` must be a boolean type. Value range constraint verification ensures numeric fields are within valid ranges; for example, priority fields have a value range of 0-999, and values outside this range are automatically truncated to the boundary value. Referential integrity verification checks for missing or circular dependencies between packages, achieved by constructing a reference graph and executing a cycle detection algorithm.
[0072] After static validation, semantic validation is performed. Package dependency validation uses a topological sorting algorithm to detect whether dependencies form a directed acyclic graph. If a circular dependency is detected, the smallest dependency cycle is marked and the developer is prompted to resolve it. Interface specification consistency validation checks whether the interface implementation matches the declaration, including parameter types, number of parameters, and return value types. Lifecycle rule conflict detection identifies logical conflicts between rules, such as contradictory actions under the same condition or rule combinations that may lead to deadlock.
[0073] During the adaptive optimization phase, a performance monitoring mechanism based on a sliding time window is constructed. This mechanism maintains a 30-minute sliding window and collects performance metrics every 5 seconds. Subpackage loading time is obtained by recording the time interval from the start of the `loadSubpackage` call to the completion of page rendering; the normal value should be controlled within 500 milliseconds. Memory usage trends are constructed using continuously collected memory usage data; under normal circumstances, the growth rate should not exceed 5% per minute. CPU usage is obtained through a native interface to obtain the current process's CPU usage percentage; the peak should not consistently exceed 80%. Network throughput records the number of network requests and data transmission per second; in a typical 4G network environment, it should be kept below 150KB / s to avoid excessive user data consumption. Interaction response latency is measured from the time interval between user operation and interface response; it should be controlled within 100 milliseconds to ensure a good user experience. Resource usage includes the number and size of subpackages resident in memory; under normal circumstances, it should not exceed 5 active subpackages. Page access frequency statistics record the number of times each page is accessed and the dwell time within 30 minutes to predict user paths.
[0074] Based on collected performance metrics, a state evaluation algorithm is executed. This algorithm standardizes each metric and compares it with a target threshold to calculate a performance score. A performance score below 70 triggers configuration parameter adjustments. Lifecycle rule threshold adjustments primarily target state transition time conditions; for example, when memory pressure is high, the time threshold for freezing to releasing is shortened from 120 seconds to 60 seconds. Component hierarchy priority adjustments are based on page access frequency and component importance. Components within the page are first divided into three levels: core rendering components (such as page frames and main content areas), auxiliary interactive components (such as buttons and forms), and decorative components (such as background images and dividers). The system assigns basic priorities based on the component's position in the viewport, with visible components receiving higher priority. Simultaneously, combined with historical access data, components in frequently accessed areas receive additional priority, ultimately forming a priority score of 1-10. Components with priority 10 are loaded and rendered first, and components with priority 1 are loaded last. Scheduling strategy parameter adjustments target the resource scheduling layer's operating mechanism, including thread pool capacity and scheduling algorithm parameters. The thread pool capacity is dynamically adjusted based on the number of CPU cores and the current load. A standard eight-core device defaults to four worker threads. When the CPU load is consistently low (<30%), one thread is added every 30 seconds until the maximum of eight is reached. When the load is high (>70%), one thread is reduced every 15 seconds until the minimum of two is reached. Scheduling algorithm parameters include task queue priority weights and time slice allocation ratios. The system adjusts the weights of various task types based on the current task type distribution. Computationally intensive tasks receive more resources when the CPU load is low, and network I / O tasks receive higher priority when the network is good. The memory reclamation threshold is adjusted based on memory usage trends. When the trend is continuously rising, the reclamation threshold is lowered, changing from triggering at 85% memory usage to triggering at 75%.
[0075] All parameter adjustments are subject to boundary checks to ensure that the adjusted parameters remain within safe ranges. For example, the thread pool size is limited to 2-8, the state transition time threshold is limited to 30-300 seconds, and the memory reclamation threshold is limited to 60%-90%. Adjustments exceeding these limits will be automatically truncated to the boundary values.
[0076] Configuration updates employ an incremental rollback mechanism and a canary release strategy. The incremental rollback mechanism saves configuration snapshots of the last 5 versions, with each configuration change initially taking effect on 10% of user devices. The system continuously monitors the performance metrics of these devices; if a metric deviates from the target range for three consecutive samples, a rollback operation is triggered, restoring to the previous stable version. After 15 minutes of performance stabilization, the configuration change is expanded to 50% of user devices, and after another 15 minutes of stabilization, a full release is conducted.
[0077] This technical solution ensures the correctness and consistency of configuration through multi-level configuration verification, avoiding operational anomalies caused by configuration errors. Through real-time performance monitoring and adaptive configuration adjustment, the mini-program can dynamically optimize resource loading strategies based on the operating environment and user behavior characteristics, effectively improving loading performance and user experience. The incremental rollback mechanism and canary release strategy ensure the security and stability of configuration updates, maintaining reliable system operation even in complex network environments and under diverse device conditions.
[0078] In one alternative implementation,
[0079] Based on the subpackage structure template, a subpackage resource list is created, including a list of code files, a list of style files, a list of static resource files, and inter-subpackage dependency declarations, including:
[0080] A four-layer structure is adopted to organize the subpackage resources, including the code file layer, style file layer, static resource layer and dependency declaration layer; a subpackage resource list is established based on the four-layer structure, and resource scanning is performed on each layer to generate a set of code files, a set of style files and a set of static resource files;
[0081] By scanning the code reference statements in the code file set, the style reference statements in the style file set, and the resource inline references in the static resource file set, dependency reference information between sub-packages is collected, and a dependency declaration set containing source sub-package identifier, target sub-package identifier, and dependency weight is generated based on the dependency reference information.
[0082] Extract the path, size, hash value, and type attribute information of each resource file in the subpackage resource list, and determine the resource file attributes used for subpackage loading priority sorting based on the weighted calculation results of real-time access frequency, dependency reference count in the dependency declaration set, and file size according to the preset weighting coefficient;
[0083] An incremental update mechanism is established. By monitoring changes to subpackaged resources and calculating changes in the hash values of resource files, the dependency reference information in the dependency declaration set is updated, and the priority attributes of resource files in the subpackaged resource list are recalculated based on the updated dependency reference information.
[0084] For example, the four-layer structure includes: a code file layer, a style file layer, a static resource layer, and a dependency declaration layer. The code file layer manages script files such as JavaScript and TypeScript; the style file layer manages style files such as CSS, LESS, and SCSS; the static resource layer manages media resources such as images, fonts, and audio; and the dependency declaration layer records the dependency relationships between the resources in the above three layers.
[0085] When building a resource list based on a four-layer structure, resource scanning is performed at each layer. The code file layer scanning combines static and runtime analysis. The static analysis stage uses an Abstract Syntax Tree (AST) parser to parse code files and identify explicit import statements such as `import` and `require`. The runtime analysis stage simulates code execution in a sandbox environment to capture implicit references such as `eval` and dynamic `import`. For example, for a mini-program with 20 pages, static analysis can identify an average of 93% of code dependencies, while runtime analysis supplements this by capturing the remaining 7% of dynamic dependencies. The style file layer scanning uses a CSS parser to extract `@import` directives, `url()` functions, and inline style references. For complex nested stylesheets, recursive parsing is performed until the complete dependency chain is obtained. The static resource layer scanning uses a multi-pattern matching algorithm to identify resource paths such as images, audio, and video referenced in code and style files, while also classifying resources based on file extensions and MIME types.
[0086] In the dependency identification stage, a complete dependency network is constructed by scanning the resource reference information collected in the first three layers. Code reference statement analysis extracts module paths from import / require statements through lexical analysis; style reference statement analysis identifies @import and url() references in CSS; and resource inline reference analysis detects attribute values such as src and href in HTML / XML tags. This reference information is converted into standardized dependency declarations, each containing three key attributes: source package identifier (representing the referrer's package ID), target package identifier (representing the referenced package ID), and dependency weight.
[0087] Dependency weight calculation considers three factors: reference frequency, reference location, and reference type. Reference frequency represents the number of times the same reference appears in the subpackage; higher frequency means higher weight. Reference location distinguishes between references required for initial screen rendering and references loaded on demand; the former has a higher weight. Reference type distinguishes between strong dependencies (such as business logic dependencies) and weak dependencies (such as decorative resources); strong dependencies have a higher weight. For example, in an e-commerce mini-program, the dependency weight of the product details page on the product information interface is 0.9 (high-frequency critical business dependency), while the dependency weight on decorative icons is 0.3 (low-frequency weak dependency).
[0088] After the dependency declaration set is built, detailed attribute information of the resource files is extracted, including path, size, hash value, and type. File paths are stored in relative path format for easy cross-environment portability; file sizes are recorded in bytes for evaluating loading overhead; file hash values are generated using the SHA-256 algorithm to uniquely identify file content and detect changes; file types are determined based on extension and content characteristics, and are divided into five categories: code, style, image, media, and configuration.
[0089] Resource file priority calculation integrates data from three dimensions: real-time access frequency, dependency reference count, and file size. Real-time access frequency is obtained by monitoring user behavior, recording the number of times each resource is accessed within a recent period (default 7 days); dependency reference count is calculated from the dependency declaration set; file size affects loading performance, with smaller files typically receiving higher priority. A weighted calculation method is used to determine the final priority: access frequency is weighted at 0.5, dependency reference count at 0.3, and file size at 0.2 (the weight is inversely proportional to the file size, meaning smaller files contribute more weight).
[0090] To address resource change scenarios, an incremental update mechanism is established. A file monitoring service continuously listens for changes in subpackage resources, capturing events such as additions, modifications, and deletions. When a file change is detected, the system calculates the hash value of the new file and compares it with historical records. For changed files, the system analyzes the scope of impact: if it's an independent resource change, only the dependencies related to that resource are updated; if it's a shared resource change, all subpackage dependencies referencing that resource are updated. During incremental updates, a change set is maintained, recording a table comparing the original and new hash values of modified resources. Based on this change set, the system performs a partial update of dependency reference information, only rescanning the changed files and their directly related files, rather than rebuilding all dependencies. After the update, the system recalculates the priority attributes of the affected resources based on the new dependency reference information.
[0091] The scope of changes is identified and marked using a difference detection algorithm, and three update strategies are adopted: fine-grained update (single resource change), medium-grained update (component-level change), and coarse-grained update (sub-package-level change).
[0092] This technical solution achieves clear classification and efficient management of subpackaged resources through a four-layer resource structure, accurately captures the reference relationships between resources through a dependency declaration mechanism, integrates multi-dimensional data through a priority calculation strategy to ensure that critical resources are loaded first, and significantly reduces the cost of resource changes through an incremental update mechanism. It improves the loading performance and user experience of mini-programs, reduces development and maintenance costs, and provides a solid technical foundation for mini-program development in complex business scenarios.
[0093] In one alternative implementation,
[0094] Constructing a sub-package lifecycle state machine based on the aforementioned sub-package state definition includes:
[0095] The state machine includes six states: pending loading, loading, loaded, activated, frozen, and pending release, and sets state transition trigger conditions and transition rules. The state machine sets different state transition strategies according to component type. Basic components remain stable after entering the activated state, business components are converted to the frozen state when switching pages, and extended components are given priority to enter the frozen state. The state machine obtains the system memory usage in real time through the memory monitoring module. When the memory usage exceeds the preset threshold, it automatically converts the least used loaded sub-packages to the frozen state and releases the memory resources they occupy.
[0096] For example, the subpackage lifecycle state machine adopts a finite state automaton model. By defining six core states of subpackages and their transition rules, it achieves refined management and efficient scheduling of subpackage resources. The six core states include: pending loading, loading, loaded, activated, frozen, and pending release.
[0097] The "Pending Loading" state is the initial state of the subpackage, indicating that the subpackage has not yet started loading. At this time, the subpackage resources do not occupy memory space, and only metadata records exist in the subpackage index table. The "Loading" state indicates that the subpackage is being loaded from storage media or the network into memory. During this process, the subpackage manager tracks the loading progress in real time and provides loading percentage feedback. The system has a timeout protection mechanism for the "Loading" state, with a default timeout threshold of 10 seconds. After a timeout, it automatically retryes, up to a maximum of 3 retries. The "Loaded" state indicates that all resource files of the subpackage have been loaded but initialization has not yet been performed. At this time, code files and resource files have been loaded into memory, but the JavaScript context environment has not yet been created. The "Activated" state is the fully running state of the subpackage, indicating that the subpackage has been initialized and is in active use. At this time, the JavaScript context environment has been created, view components have been rendered, and the subpackage can respond to user interactions. The "Frozen" state is a critical state for resource optimization, indicating that the subpackage is temporarily not used but may be reactivated. At this time, the JavaScript context environment of the subpackage is maintained, but some non-critical view resources may be released, such as image caches and audio resources. The "pending release" status indicates that the subpackage is about to be unloaded, with only the necessary metadata retained for reloading, and all occupied memory resources will be released.
[0098] State transitions are jointly controlled by triggering conditions and transition rules. The transition from pending loading to loading is triggered by page navigation events or preloading strategies; the transition from loading to loaded is triggered by resource loading completion events; the transition from loaded to activated is triggered by initialization completion events; the transition from activated to frozen is triggered by page leaving the visible area, user inactivity for an extended period (default threshold is 180 seconds), or memory pressure events; the transition from frozen to pending release is triggered by prolonged inactivity for an extended period (default threshold is 300 seconds) or severe memory pressure events; and the transition from pending release to pending loading is triggered by resource release completion events.
[0099] The state machine implements differentiated transition strategies for different component types. Basic components, the core components of the mini-program framework, such as routing management, the event system, and communication mechanisms, remain stable once activated and do not easily enter a frozen state, ensuring the continued availability of the mini-program's basic functions. Business components implement specific business functions, such as product lists, order management, and payment processes. When a user leaves the relevant page, these components transition from an activated state to a frozen state, preserving the context but releasing some resources. Extension components provide additional functionality, such as third-party sharing, data analysis, and ad display. These components prioritize entering the frozen state, and may even directly enter a pending release state when memory pressure is high.
[0100] For example, the payment core module of an e-commerce mini-program, as a basic component, has its state transition threshold set as follows: it is only considered to freeze after more than 720 seconds of inactivity, and is only considered to be released after the frozen state lasts for 1800 seconds; the product details page, as a business component, enters a frozen state after 120 seconds of inactivity, and is considered to be released after the frozen state lasts for 600 seconds; the advertising display module, as an extended component, enters a frozen state after 60 seconds of inactivity, and is considered to be released after the frozen state lasts for 300 seconds.
[0101] The state machine integrates a memory monitoring module to achieve adaptive management based on system resource status. The memory monitoring module uses a lightweight sampling method, sampling system memory usage every 30 seconds by default, recording metrics such as total memory, available memory, and memory usage by the current application. The system has three memory pressure thresholds: mild pressure (70% utilization), moderate pressure (80% utilization), and severe pressure (90% utilization).
[0102] When memory pressure is detected, the state machine triggers a gradient resource release process. Under mild pressure, the system shortens the duration of frozen states, reducing the freeze threshold for extended components from 300 seconds to 150 seconds. Under moderate pressure, in addition to shortening the threshold, it also proactively converts least-used (LRU) activated extended components to a frozen state. Under heavy pressure, the system adopts a more aggressive strategy, marking all extended components and non-current page business components as pending release and forcibly executing garbage collection.
[0103] The LRU (Least Recently Used) algorithm in adaptive memory management is implemented by maintaining a record of packet usage. The system maintains an access timestamp and an access frequency counter for each loaded packet, and determines a packet's usage frequency score based on a weighted combination of these two. When memory needs to be released, the system sorts the packets according to their scores, prioritizing the release of packets with lower scores. For example, in a social mini-program, the Moments packet has a score of 85, the Message List packet has a score of 92, while the rarely used Game Center packet has a score of only 31. When memory pressure is triggered, the system will prioritize releasing resources from the Game Center packet.
[0104] The state machine also enables predictive state transition optimization. By analyzing users' historical behavior patterns, the system can predict which pages a user might visit and proactively restore relevant sub-packages from a frozen state to an active state, or promote a pending loading state to a loaded state.
[0105] This technical solution achieves refined lifecycle management of subpackaged resources through a six-state model. The differentiated component strategy ensures the stability of core functions and the flexibility of extended functions. The memory adaptive management mechanism effectively copes with complex and ever-changing system resource conditions. It reduces the memory consumption of the mini-program, improves system response speed and stability, optimizes user experience, and provides developers with powerful and easy-to-use resource management capabilities, reducing development and maintenance costs.
[0106] In one alternative implementation,
[0107] Based on the target page path information and the sub-package resource list, a directed acyclic sub-package dependency graph is constructed. The target sub-package node and its predecessor dependency nodes are determined by a graph traversal algorithm, including:
[0108] Based on the target page path information, obtain the initial set of subpackage nodes that have a direct reference relationship with the target page from the subpackage resource list; starting from the initial set of subpackage nodes, recursively construct the subpackage dependency graph based on the dependency declaration set, and use the source subpackage identifier and target subpackage identifier in the dependency declaration set as the source node and target node of the dependency graph, respectively, and the dependency weight as the weight attribute of the connecting edge, wherein the direction of the directed edge is the dependency pointing to the dependent;
[0109] A depth-first traversal is performed on the sub-package dependency graph, recording the node access timestamp and earliest reachable timestamp during the traversal process. Cycles are identified, and the edge with the lowest dependency weight in the identified cycle is marked as an unnecessary dependency edge. After removing the unnecessary dependency edges, a breadth-first traversal algorithm is used to hierarchically mark the sub-package nodes, grouping sub-package nodes at the same level into the same set, and determining the set of preceding dependent nodes for each sub-package node. The access order of the nodes is the loading priority order of the sub-packages.
[0110] For example, the initial set of subpackage nodes is obtained from the subpackage resource list based on the target page path information. The target page path is usually triggered by user navigation behavior, such as clicking a page link, switching tabs, or automatic system redirection. After receiving the target page path, the system queries the page mapping table in the subpackage resource list to determine the subpackage to which the page belongs. At the same time, the system retrieves related subpackages that have direct reference relationships with the target page. These reference relationships include component reuse between pages, shared data access, and function calls. For example, in an e-commerce mini-program, when a user visits the "product details page" (path " / pages / detail / goods"), the system finds that this page belongs to the "product module subpackage" and has direct references to the "shopping cart subpackage" and the "payment subpackage". These three subpackages constitute the initial set of subpackage nodes.
[0111] Starting with an initial set of sub-package nodes, a complete sub-package dependency graph is recursively constructed based on a set of dependency declarations. This set contains all dependency relationships between sub-packages, and each declaration includes three core attributes: source sub-package identifier, target sub-package identifier, and dependency weight. The source sub-package identifier represents the referrer, the target sub-package identifier represents the referenced party, and the dependency weight represents the strength of the dependency relationship. The system converts dependency declarations into directed edges in the dependency graph, with the direction pointing from the source node to the target node, representing a "dependency points to the dependent" relationship. For example, the dependency declaration "Shopping cart sub-package depends on product data sub-package, weight 0.8" is converted into a directed edge from the shopping cart sub-package node to the product data sub-package node with a weight of 0.8.
[0112] The dependency graph is constructed recursively. Initial sub-package nodes are added to the graph. Then, for each node, its dependent target sub-packages are queried, and these target sub-packages are added as new nodes to the graph, with corresponding directed edges created. This process is repeated for newly added nodes until no more nodes are added. To avoid redundant processing, a set of visited nodes is maintained to ensure that each node is processed only once.
[0113] The constructed dependency graph may contain cycles, i.e., circular dependencies where A depends on B, B depends on C, and C depends on A. Cycles can cause loading order to be unpredictable, therefore cycle detection and elimination are necessary. A depth-first search (DFS) algorithm is used to traverse the graph, recording two key timestamps: the node access timestamp (representing the time a node is first visited) and the earliest reachable timestamp (representing the earliest reachable time from the current node via backward edges). When a node's earliest reachable timestamp is found to be less than the access timestamp of its current child node, a cycle is detected. Once a cycle is detected, appropriate dependency edges are selected for severing to eliminate the circular dependency. The severing strategy is based on dependency weights, prioritizing severing the dependency edges with the lowest weights. For example, in a social mini-program, if a cycle "Moments sub-package → User information sub-package → Message sub-package → Moments sub-package" is detected, where the weights of the three edges are 0.85, 0.72, and 0.43 respectively, the system will choose to sever the dependency edge "Message sub-package → Moments sub-package" with a weight of 0.43.
[0114] After loop elimination, the dependency graph transforms into a directed acyclic graph (DAG). At this point, the system uses a breadth-first search (BFS) algorithm to hierarchically label the nodes. Starting with a node with an in-degree of 0 (i.e., a node not depended on by any other node), it is labeled as level 1. Then, all nodes that the node directly depends on are visited and labeled as level 2, and so on. Nodes within the same level have no dependencies and can be loaded in parallel. In certain special cases where there are no nodes with an in-degree of 0, the system will start layering from the node with the fewest dependencies. In a typical mini-program's sub-package structure, the layering result is usually 3-5 levels. For example, the basic framework is sub-packaged at level 1, functional modules at level 2, business pages at level 3, and extended functions at level 4.
[0115] After node layering is completed, the system determines the set of preceding dependent nodes for each sub-package node. For a node at level n, its preceding dependent nodes are the nodes directly connected to it from levels 1 to n-1. These preceding dependent nodes must be loaded before the target node. For example, the "order confirmation sub-package" at level 3 may depend on the "user information sub-package" at level 1 and the "product data sub-package" at level 2, and these two sub-packages constitute its set of preceding dependent nodes.
[0116] The loading priority of sub-packages is determined based on hierarchical information and prerequisite dependencies, sorted from low to high hierarchy. Nodes at the same level are further sorted based on the following factors: the out-degree of the node (number of times it is depended on), with higher out-degree indicating higher priority; the cumulative weight of dependent edges, with higher weights indicating higher priority; and the size of the sub-package, with smaller packages having slightly higher priority. This ultimately forms a complete loading sequence, ensuring that prerequisite dependencies are always loaded before subsequent nodes.
[0117] For example, in the scenario of a product details page in an e-commerce mini-program, the following loading sequence might be generated: Layer 1 (core framework sub-package, 4MB) → Layer 1 (network request sub-package, 1.2MB) → Layer 2 (user information sub-package, 2.5MB) → Layer 2 (product data sub-package, 3.8MB) → Layer 3 (product details sub-package, 5.1MB) → Layer 3 (comment sub-package, 2.7MB) → Layer 4 (related recommendation sub-package, 4.3MB). This loading order ensures that core functions are loaded first, while also satisfying dependency constraints.
[0118] This embodiment also includes a dynamic optimization mechanism for the loading process. When an abnormal loading or timeout is detected in a sub-package during the actual loading process, the system can dynamically adjust the loading order of subsequent sub-packages, delaying the loading of non-critical sub-packages or adopting a degradation strategy to ensure that core functions are not affected. For example, if the "comments sub-package" fails to load, the system can continue to load the "related recommendations sub-package" and display a message on the interface indicating that the comments function is unavailable, instead of blocking the loading of the entire page.
[0119] This technical solution achieves accurate modeling and efficient management of complex dependencies between packages by constructing a directed acyclic sub-package dependency graph and an intelligent graph traversal algorithm. The loop detection and elimination mechanism effectively solves the circular dependency problem, and the node layering and priority sorting strategy ensures the rationality and efficiency of the loading order. It improves the loading speed and stability of the mini-program, reduces resource consumption, optimizes the user experience, and provides developers with a clear sub-package dependency management mechanism, simplifying the development process and improving development efficiency.
[0120] In one alternative implementation,
[0121] Resource scheduling includes:
[0122] A resource scheduling layer is used to implement resource scheduling. The resource scheduling layer includes a multi-level parallel scheduling system, with a first scheduler for scheduling code files, a second scheduler for scheduling style files, and a third scheduler for scheduling static resource files. Each scheduler includes an independent task queue and a dynamically expandable and shrinkable thread pool. The capacity of the thread pool is dynamically adjusted according to the current CPU utilization, memory utilization, and network status of the device. During the loading process, the execution status of tasks in each scheduler is monitored in real time. When an abnormal task execution is detected, an automatic retry mechanism is triggered. If the number of retries exceeds a preset threshold, the corresponding resource is switched to a locally preset degraded resource.
[0123] A distributed resource pool is constructed to support the multi-level parallel scheduling system. Packaged resources are stored in a code resource pool, a style resource pool, and a static resource pool, respectively, according to their type. The distributed resource pool adopts a fragmented storage mechanism, where each resource fragment includes resource content, resource feature values, and a resource reference count. When multiple packages are detected referencing the same resource, duplicate resources are identified through resource feature value matching, and only one copy of the resource is retained in the resource pool. Other packages reference this resource copy through a resource mapping table. The loading priority of the preceding dependent nodes is higher than that of the target package nodes.
[0124] For example, the subpackage runtime manager, as the core control center for loading subpackages in a mini-program, consists of a three-layer architecture: a unified interface layer, a lifecycle management layer, and a resource scheduling layer. The unified interface layer provides standardized subpackage operation APIs, encapsulates the complex underlying implementation, and provides a concise and unified interface to upper-layer applications. The lifecycle management layer, based on the aforementioned six-state model, is responsible for subpackage state transitions and lifecycle event handling.
[0125] The resource scheduling layer implements a multi-level parallel scheduling system, divided into three dedicated schedulers based on resource type: the first scheduler is responsible for code file scheduling, the second scheduler for style file scheduling, and the third scheduler for static resource file scheduling. This categorized scheduling design considers the loading characteristics and priority differences of different types of resources. Code files directly affect the implementation of functions and have the highest priority; style files affect the interface display and have the next highest priority; static resource files, such as images and audio, can be loaded lazily and have the lowest priority.
[0126] Each scheduler's internal structure includes an independent task queue and thread pool. The task queue is implemented using a priority queue, and each loaded task contains the following attributes: resource path, resource type, priority score, timeout, and retry count. The priority score is calculated based on resource importance, user visibility, and dependencies, ranging from 1 to 10, with higher values indicating higher priority. For example, the framework code file necessary for the first screen rendering has a priority of 10, while decorative images in areas not visible on the first screen have a priority of 3. The queue supports dynamic insertion and adjustment; when a high-priority task appears, it can be immediately inserted at the head of the queue to await execution.
[0127] The thread pool employs a work-stealing strategy, dynamically adjusting the thread pool capacity of each scheduler based on system status. In the initial configuration, the code file scheduler allocates 4 threads by default, the style file scheduler allocates 2 threads, and the static resource scheduler allocates 2 threads. The dynamic adjustment of the thread pool capacity is based on three key metrics: CPU utilization, memory utilization, and network status. When CPU utilization is below 30%, the system adds one worker thread every 15 seconds until the preset limit is reached (8 threads for the code scheduler, and 4 threads each for the style and static resource schedulers). When CPU utilization is above 75%, the system reduces one worker thread every 10 seconds until the preset lower limit is reached (each scheduler retains a minimum of 1 thread). Similarly, when available memory is below 25%, the system reduces worker threads to lower memory pressure; when network conditions deteriorate (RTT exceeds 300ms), the system increases the number of threads in the static resource scheduler to process more download tasks in parallel, improving overall throughput. For example, when running a large e-commerce mini-program on a high-end device, if the system detects that the CPU usage is 20% and there is sufficient memory, it will dynamically adjust to: 8 threads for the code scheduler, 4 threads for the style scheduler, and 4 threads for the static resource scheduler. On a low-end device, if the system detects that the CPU usage is 85%, it will automatically adjust to: 2 threads for the code scheduler, 1 thread for the style scheduler, and 1 thread for the static resource scheduler to reduce the system load.
[0128] During resource loading, the task execution status is monitored in real time, and an intelligent retry strategy is implemented for tasks with execution errors. Error types include: network timeout (connection not responding for more than 5 seconds), loading failure (HTTP error code), and parsing error (file corruption). Different retry strategies are used for different error types: network timeouts use an exponential backoff algorithm with an initial delay of 200ms, followed by retry intervals of 400ms, 800ms, etc.; loading failures immediately switch to a backup CDN node for retrying; parsing errors directly attempt to use the local cached version. Different maximum retries are set for each type of resource: code files can be retried a maximum of 3 times, style files a maximum of 2 times, and static resources a maximum of 1 time. When the number of retries exceeds the threshold, the system activates a degradation mechanism, switching the corresponding resource to a locally pre-configured degradation resource. Degradation resources are divided into three levels: complete degradation resources (fully functional but possibly with simplified styles), basic degradation resources (retaining core functionality), and fallback degradation resources (only displaying error messages). For example, if a product image fails to load on a product details page, first try using an old image cached locally. If there is no cache, use a generic product placeholder image to ensure that the interface does not appear blank.
[0129] To complement the multi-level parallel scheduling system, a distributed resource pool is constructed, divided into code resource pool, style resource pool, and static resource pool according to resource type. The distributed resource pool employs a fragmented storage mechanism, dividing large resource files into multiple smaller resource fragments for management. Each resource fragment contains three key attributes: resource content (actual data), resource feature value (unique identifier), and resource reference count (number of times it has been referenced). The resource feature value is generated by calculating a SHA-256 hash value from the resource content, used to uniquely identify the resource content; even if the filenames are different, resources with the same content will generate the same feature value. The resource reference count records the number of times the resource is referenced by different fragments, initially with a value of 1, incrementing by 1 for each new reference and decrementing by 1 for each new reference. When the count reaches 0, the resource can be reclaimed.
[0130] Duplicate resources are identified through resource feature value matching technology. When a new resource is added to the resource pool, its feature value is first calculated, and then the pool is searched for resources with the same feature value. If a resource with the same feature value exists, it is not stored again. Instead, a resource mapping relationship is established, and the reference count of the original resource is incremented by 1. For example, multiple business subpackages may use the same icon file, even though the paths are different (e.g., " / packageA / icons / home.png" and " / packageB / assets / home.png"). Since the calculated feature values are the same, the system will only keep one copy in the static resource pool, and other references will be directed to this copy through the resource mapping table.
[0131] For example, a certain e-commerce mini-program contained over 2,500 resource files across 30 sub-packages. Feature value matching technology identified approximately 35% of the resources as duplicates, ultimately requiring only 1,625 unique resources to be stored, saving about 350MB of memory. For frequently repeated resources, such as brand logos and generic icons, their reference counts can reach 15-20, indicating they are used by multiple sub-packages.
[0132] The resource pool's fragmented storage mechanism is particularly effective for large resources. For example, a 4MB video resource can be divided into 16 256KB fragments, each managed independently. This design offers two advantages: first, it enables fine-grained memory management, allowing only partial fragments of the resource to be loaded; second, it supports parallel loading, enabling multiple fragments to be processed simultaneously by different threads. In video playback scenarios, the system prioritizes loading the first few fragments to ensure playback begins, with subsequent fragments loaded gradually during playback.
[0133] The resource pool also implements an intelligent caching strategy. Frequently accessed resources (high reference count and high access frequency) are marked as "resident resources" and are preferentially retained in memory; large resources (such as high-definition images and long videos) are marked as "on-demand resources," loaded when needed and released when not in use; important but infrequently used resources (such as payment components) are marked as "preloaded resources," preloaded when system resources are sufficient and released when resources are scarce. The system periodically (every 30 minutes by default) analyzes resource access patterns and dynamically adjusts the resource caching strategy markings accordingly.
[0134] Pre-dependent nodes are prioritized over target sub-package nodes in the loading order to ensure that dependencies are satisfied. The system determines the dependencies between nodes through dependency graph analysis and designs the loading order accordingly. For example, if sub-package A depends on sub-packages B and C, and sub-package B depends on sub-package D, the final loading priority order is: D→B→C→A, ensuring that all dependencies are ready before the target sub-package is loaded.
[0135] This technical solution achieves differentiated loading and optimization of different types of resources through a multi-level parallel scheduling system. The dynamically adjusted thread pool effectively adapts to various device capabilities and operating environments, and the exception handling and degradation mechanisms greatly improve system stability. The distributed resource pool design significantly reduces memory consumption and improves resource utilization efficiency. Feature value matching technology eliminates duplicate resource storage, and the sharded storage mechanism optimizes the loading experience of large resources. It ensures the smooth operation of the mini-program while minimizing system resource consumption, providing a solid foundation for the stable and efficient operation of the mini-program on diverse devices.
[0136] In one alternative implementation,
[0137] The sub-package loading process, executed through the sub-package runtime manager, includes on-demand loading and page rendering of the target sub-package, including:
[0138] The component hierarchy is prioritized based on the priority attributes of resource files in the subpackage resource list. The target subpackage is divided into three levels: basic components, business components, and extended components. The basic components are used to build the DOM tree structure and implement user interaction functions, and are loaded synchronously with the page. The business components are used to implement data processing and functional operations, and are loaded when the page enters the visible area. The extended components are used to implement independent functional modules and are loaded when a user operation event is received. When the system memory usage exceeds a first preset threshold or the CPU usage exceeds a second preset threshold, the loading of the extended components is interrupted.
[0139] A layered rendering strategy is adopted. After the basic components are loaded, the page framework is rendered first. After the business components are loaded, the content of the visible area is rendered. For list-type data, virtual scrolling is used to optimize rendering performance. Extended components update the page content through asynchronous rendering mode, and the rendering task is split into several micro-tasks to be executed in time.
[0140] For example, at the start of the subpackage loading process, the component hierarchy priority is first set. Based on the resource file priority attributes in the subpackage resource manifest, the components within the target subpackage are hierarchically divided. The component hierarchy adopts a three-layer structure: basic component layer, business component layer, and extended component layer.
[0141] Basic components are used to build the DOM tree structure and implement user interaction functions. They are the core elements of the page skeleton and directly determine the initial framework construction effect of the page. These components include basic DOM structure elements such as page container elements, navigation bars, tab bars, and layout frames, as well as basic interactive components such as buttons and input boxes. Basic components are typically small in code (average 5-10KB), stable in function, and referenced by multiple pages. A synchronous loading strategy with the highest priority is implemented for basic components to ensure they load synchronously with the main page, without delaying the DOM tree construction process. Two key technologies are used to ensure loading efficiency for basic components: first, preloading technology, which requests basic component resources in advance at the moment the mini-program starts or the page jump decision is made; second, persistent memory technology, which prevents basic components from being garbage collected by the garbage collection mechanism by adding the "persistent:true" tag to the component metadata. In a typical e-commerce mini-program, the total resource size of the basic components required for DOM tree construction (such as page containers, top navigation bars, bottom tab bars, product grid containers, etc.) is approximately 150KB. The system ensures that its loading time is controlled within 100ms, so that users can immediately see the complete page DOM structure framework after opening the page.
[0142] Business components are responsible for implementing specific business functions, including data display, user interaction, and business logic, such as product lists, order information, and user profiles. These components typically have medium resource size, relatively independent functionality, and are closely related to the current page's business logic. A visible area-triggered on-demand loading strategy is adopted: when the page scrolls to a preset distance (default 1.5 times the screen height) before the business component's area enters the visible range, the component's resources are loaded. Component visibility is monitored through the IntersectionObserver API; when a component is detected as about to enter the visible area, a resource loading request is immediately initiated. For example, a product information card on a product details page is a business component; when the user scrolls to a distance of 300px from this component, the system pre-loads the component to ensure that it has finished rendering when the user scrolls to the actual position.
[0143] Extended components provide additional functionalities or unique interactive experiences, such as video players, comment modules, and sharing functions. These components typically have large resource sizes, strong functional independence, and relatively little impact on the user's core task path. An event-triggered lazy loading strategy is implemented for extended components: the corresponding component is loaded only when the user actually performs an action (such as clicking a relevant button) or is about to perform an action (such as hovering a finger). Extended components also implement resource placeholder technology; even if the component has not yet loaded, a suitable placeholder interface will be displayed to indicate to the user that the function exists but is not yet ready. For example, the video player component, as an extended component, only loads the complete player resource (approximately 3MB) when the user clicks the play button, displaying the video cover image and loading animation before loading.
[0144] The component prioritization process incorporates multiple evaluation factors: resource dependencies (weight 0.3), user interaction frequency (weight 0.3), resource size (weight 0.2), and loading performance (weight 0.2). User interaction data is continuously collected during operation to dynamically adjust component priorities. For example, for users who frequently use payment functions, the priority of payment-related components is automatically increased; for users who primarily browse products, the priority of product display components is correspondingly increased.
[0145] To ensure system stability, a resource protection mechanism is triggered when memory usage exceeds the first preset threshold (default 75%) or CPU usage exceeds the second preset threshold (default 80%). This interrupts the loading of extended components and releases loaded but unused extended component resources. Priority is given to ensuring the normal operation of basic and business components, ensuring the availability of core functions. The recovery conditions are: memory usage remains below 80% (60%) of the first preset threshold for 30 consecutive seconds, and CPU usage remains below 80% (64%) of the second preset threshold for 30 consecutive seconds.
[0146] In terms of rendering strategy, a layered rendering mechanism is adopted, which divides the page rendering process into three stages, corresponding to the component level: skeleton rendering stage, content rendering stage, and enhancement rendering stage.
[0147] The skeleton rendering phase executes immediately after the basic components are loaded. It's responsible for building the page's basic DOM structure and layout framework. First, it renders the page container and key layout elements. Then, it creates placeholder elements for unloaded content, using a size and shape similar to the final content to prevent layout jumps caused by subsequent rendering. In large e-commerce platform mini-programs, the skeleton rendering phase typically completes within 200ms, ensuring users receive rapid visual feedback. Skeleton screen technology is the core optimization method in this phase. The system pre-generates skeleton screen templates that match the page structure, consisting of simple color blocks and lines. These are extremely small (usually <10KB) and load quickly, effectively reducing user anxiety during waits.
[0148] The content rendering phase executes after the business components have loaded, and is responsible for populating the main content of the page. This phase adopts a viewport-first rendering strategy, rendering content visible within the user's viewport first, and then gradually rendering content outside the viewport. For list-type data, virtual scrolling technology is used: only the list items in the current viewport and its upper and lower buffers (defaulting to 1 times the height of the viewport) are rendered; the remaining list items only store data without creating DOM elements. When the user scrolls, new elements are dynamically created to enter the viewport and elements leaving the viewport are recycled. Practice shows that for a list of 1000 product data items, using virtual scrolling technology can control the number of actually created DOM elements to 30-50, reduce memory usage by more than 90%, and improve scrolling performance by 45%.
[0149] The enhanced rendering phase executes after the extended components have loaded, responsible for adding extra functionality and interactive elements. This phase employs an asynchronous rendering model, breaking down the rendering task into multiple micro-tasks and executing them in a time-sharing manner to avoid blocking the main thread. Based on component complexity and priority, the system divides the rendering task into micro-task blocks of 5-15ms in size, executing these micro-tasks when the browser is idle (detected via the requestIdleCallback API). For example, the rendering of the comment list component is broken down into: creating the container (5ms) → rendering the first 10 comments (10ms) → rendering the like and reply buttons (8ms) → rendering the remaining comments (executed as needed). This time-sharing rendering strategy ensures that page interactions remain smooth and responsive even when rendering complex components.
[0150] This embodiment also employs an intelligent control mechanism for rendering behavior. When the system detects that a user is rapidly scrolling the page (scrolling speed exceeding 1000px / s), it will pause unnecessary rendering tasks to prioritize scrolling smoothness. When a user stays in a certain area for more than 2 seconds, the system will increase the rendering priority of components in that area, completing the loading and rendering of related content ahead of time. When there are high-energy-consuming components such as videos and maps on the page, the system will adjust the rendering strategies of other components to ensure that overall resource consumption remains within a controllable range.
[0151] For weak network environments, a progressive rendering enhancement approach is employed: first, text content (typically <20KB) is rendered; second, low-resolution versions of key images (typically <50KB) are loaded; and finally, high-resolution images and complex components are gradually replaced. This strategy ensures that even in 2G network environments, users can see relevant content within 3 seconds, significantly improving the user experience in weak network conditions.
[0152] Table 1
[0153] Table 1 illustrates the significant impact of virtual scrolling technology on list rendering performance. As the number of list items increases, the memory usage of this invention grows very slowly, requiring only 21MB of memory even with 1000 items, compared to 150MB for traditional full-scale rendering, representing an 86% reduction in memory usage. When processing 1000 list items, this invention creates only 45 DOM elements, while the traditional method requires creating all 1000 DOM elements. This design not only significantly reduces memory usage (by 86%) but also greatly reduces the computational burden of browser rendering and reflow, thereby improving scrolling performance by 45%. The table also shows a comparison of scrolling frame rates. With 1000 items, this invention maintains a smooth experience of 56fps, while the traditional method only achieves a stuttering 18fps.
[0154] Figure 3 The graph shows a comparison of page loading performance for different component loading strategies. The horizontal axis represents the number of components on the page (0-25), and the vertical axis represents the page loading time (0-2500ms). The "Invention (Three-Layer Component Division)" strategy, represented by circular data points, exhibits the best performance, with the slowest increase in loading time as the number of components increases, requiring only 840ms for 25 components. The "Traditional Full Load" strategy, represented by square data points, performs the worst, requiring 1500ms for 25 components. The "Simple Lazy Loading" strategy, represented by triangular data points, is in the middle, requiring 1250ms for 25 components. Data shows that when the number of components is 10, the three strategies require 330ms, 750ms, and 500ms respectively; when the number increases to 20, the difference widens to 655ms, 1400ms, and 1050ms. The three-layer component division strategy of this invention has a significant advantage when handling complex pages, reducing loading time by nearly 44% compared to traditional methods, effectively improving the user experience.
[0155] Existing technologies typically load subpackages as a whole, ignoring the differences in importance among components within a subpackage and lacking awareness and adaptability to system resource status. This application addresses these shortcomings by redesigning the subpackage loading mechanism at the component level, introducing component hierarchy and layered rendering strategies to achieve true on-demand loading and progressive rendering. Through refined component classification and differentiated loading strategies, it can provide an optimal user experience under various network environments and device conditions. Simultaneously, a system resource adaptive mechanism is introduced to ensure the availability of core functions even under resource constraints. This technical solution achieves refined management and priority control of subpackage resources through a three-layer component partitioning strategy; the layered rendering mechanism ensures fast user interface response and a smooth experience; virtual scrolling technology effectively solves the performance bottleneck of large data lists; asynchronous rendering mode avoids stuttering caused by main thread blocking; multi-layered resource protection mechanisms ensure stable system operation under various device conditions; and the progressive loading strategy significantly improves the user experience in weak network environments.
[0156] A second aspect of the present invention provides an electronic device, comprising:
[0157] processor;
[0158] Memory used to store processor-executable instructions;
[0159] The processor is configured to invoke instructions stored in the memory to execute the aforementioned method.
[0160] A third aspect of the present invention provides a computer-readable storage medium having stored thereon computer program instructions that, when executed by a processor, implement the aforementioned method.
[0161] This invention can be a method, apparatus, system, and / or computer program product. The computer program product may include a computer-readable storage medium having computer-readable program instructions loaded thereon for performing various aspects of the invention.
[0162] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention, and not to limit them; although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some or all of the technical features; and these modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the scope of the technical solutions of the embodiments of the present invention.
Claims
1. A method for dynamically loading subpackages on demand in mini-programs based on a unified subpackage model, characterized in that: include: Initialize standardized configuration information for the unified sub-packaging mode, including sub-packaging structure templates, sub-packaging status definitions, and sub-packaging lifecycle rules; A subpackage resource list containing resource files and inter-subpackage dependency declarations is established based on the subpackage structure template; a subpackage lifecycle state machine is constructed based on the subpackage state definition to realize subpackage lifecycle management based on state transition rules and system resource status; Based on the target page path information and the sub-package resource list, a directed acyclic sub-package dependency graph is constructed, and the target sub-package node and its predecessor dependency node are determined by the graph traversal algorithm. Establish a subpackage runtime manager, including a unified interface layer for providing standardized subpackage operation interfaces, a lifecycle management layer for managing subpackage status, and a resource scheduling layer for implementing resource scheduling; The subpackage loading process is executed through the subpackage runtime manager, which loads the target subpackage on demand and renders the page.
2. The method according to claim 1, characterized in that, The process of generating the standardized configuration information includes: Multi-level configuration verification is performed during the configuration initialization phase, including a static verification layer for structural integrity verification and reference integrity verification, and a semantic verification layer for package dependency verification and lifecycle rule conflict detection. A performance monitoring and feedback mechanism is built based on a sliding time window mechanism to collect and analyze system performance and user access data in the recent access sequence in real time to evaluate the system's operating status. Based on the evaluation results, the component hierarchy priority and scheduling strategy parameters are adaptively adjusted. The scheduling strategy parameters are used to control the dynamic adjustment of the thread pool capacity in the resource scheduling layer, and the component hierarchy priority is used to guide the component hierarchy division of the target subpackage. At the same time, parameter boundary checks limit the adjustment range of each parameter to a preset range. An incremental rollback mechanism and a canary release strategy are used for configuration updates. When any performance indicator deviates from the target range for more than a preset time, the configuration parameters are rolled back to the previous stable version.
3. The method according to claim 1, characterized in that, Based on the aforementioned subpackage structure template, a subpackage resource list containing resource files and inter-subpackage dependency declarations is established, including: The subcontracted resources are organized using a multi-layered structure. A subcontracted resource list is established based on the multi-layered structure. Resource scanning is performed on each layer to generate a set of code files, a set of style files, and a set of static resource files. By scanning the code reference statements in the code file set, the style reference statements in the style file set, and the resource inline references in the static resource file set, dependency reference information between sub-packages is collected, and a dependency declaration set containing source sub-package identifier, target sub-package identifier, and dependency weight is generated based on the dependency reference information. Extract the attribute information of each resource file in the subpackage resource list, and determine the resource file attributes used for subpackage loading priority sorting based on the weighted calculation results of real-time access frequency, dependency reference count in the dependency declaration set and file size according to the preset weighting coefficient; An incremental update mechanism is established. By monitoring changes to subpackaged resources and calculating changes in the hash values of resource files, the dependency reference information in the dependency declaration set is updated, and the priority attributes of resource files in the subpackaged resource list are recalculated based on the updated dependency reference information.
4. The method according to claim 1, characterized in that, Constructing a sub-package lifecycle state machine based on the aforementioned sub-package state definition includes: The state machine contains multiple states and is configured with state transition trigger conditions and transition rules. The state machine sets different state transition strategies according to component types. Basic components remain stable after entering the activated state, business components are converted to the frozen state when switching pages, and extended components are given priority to enter the frozen state. The state machine obtains the system memory usage in real time through a memory monitoring module. When the memory usage exceeds a preset threshold, it automatically converts the least used loaded sub-packages to the frozen state and releases the memory resources they occupy.
5. The method according to claim 3, characterized in that, Based on the target page path information and the sub-package resource list, a directed acyclic sub-package dependency graph is constructed. The target sub-package node and its predecessor dependency nodes are determined by a graph traversal algorithm, including: Based on the target page path information, obtain the initial set of subpackage nodes that have a direct reference relationship with the target page from the subpackage resource list; starting from the initial set of subpackage nodes, recursively construct the subpackage dependency graph based on the dependency declaration set, and use the source subpackage identifier and target subpackage identifier in the dependency declaration set as the source node and target node of the dependency graph, respectively, and the dependency weight as the weight attribute of the connecting edge, wherein the direction of the directed edge is the dependency pointing to the dependent; A depth-first traversal is performed on the sub-package dependency graph, recording the node access timestamp and earliest reachable timestamp during the traversal process. Cycles are identified, and the edge with the lowest dependency weight in the identified cycle is marked as an unnecessary dependency edge. After removing the unnecessary dependency edges, a breadth-first traversal algorithm is used to hierarchically mark the sub-package nodes, grouping sub-package nodes at the same level into the same set, and determining the set of preceding dependent nodes for each sub-package node. The access order of the nodes is the loading priority order of the sub-packages.
6. The method according to claim 1, characterized in that, Resource scheduling includes: The resource scheduling layer includes a multi-level parallel scheduling system with multiple schedulers. Each scheduler includes an independent task queue and a dynamically expandable and shrinkable thread pool. The capacity of the thread pool is dynamically adjusted according to the current system resource status of the device. During the loading process, the execution status of tasks in each scheduler is monitored in real time. When an abnormal task execution is detected, an automatic retry mechanism is triggered. If the number of retries exceeds a preset threshold, the corresponding resource is switched to a locally preset degraded resource. A distributed resource pool is constructed to support the multi-level parallel scheduling system. Packaged resources are stored in a code resource pool, a style resource pool, and a static resource pool, respectively, according to their type. The distributed resource pool adopts a fragmented storage mechanism, with each resource fragment including resource data and a resource reference count. When multiple packages are detected referencing the same resource, duplicate resources are identified through resource feature value matching, and only one copy of the resource is retained in the resource pool. Other packages reference this resource copy through a resource mapping table. The loading priority of the preceding dependent nodes is higher than that of the target package node.
7. The method according to claim 4, characterized in that, The sub-package loading process, executed through the sub-package runtime manager, includes on-demand loading and page rendering of the target sub-package, including: The component hierarchy is prioritized based on the priority attributes of resource files in the subpackage resource list. The target subpackage is divided into three levels: basic components, business components, and extended components. The basic components are used to build the DOM tree structure and implement user interaction functions, and are loaded synchronously with the page. The business components are used to implement data processing and functional operations, and are loaded when the page enters the visible area. The extended components are used to implement independent functional modules and are loaded when a user operation event is received. When the system memory usage exceeds a first preset threshold or the CPU usage exceeds a second preset threshold, the loading of the extended components is interrupted. A layered rendering strategy is adopted. After the basic components are loaded, the page framework is rendered first. After the business components are loaded, the content of the visible area is rendered. For list-type data, virtual scrolling is used to optimize rendering performance. Extended components update the page content through asynchronous rendering mode, and the rendering task is split into several micro-tasks to be executed in time.
8. An electronic device, characterized in that, include: processor; Memory used to store processor-executable instructions; The processor is configured to invoke instructions stored in the memory to execute the method according to any one of claims 1 to 7.
9. A computer-readable storage medium having computer program instructions stored thereon, characterized in that, When the computer program instructions are executed by the processor, they implement the method described in any one of claims 1 to 7.
Citation Information
Patent Citations
Small program compiling method and device, medium and equipment
CN116185421A
Pre-request optimization method for embedded H5 page of mobile terminal application program and storage medium
CN119884515A
Modular construction method of low-code visual interaction system
CN120406918A
Railway material purchasing asynchronous task processing method, device and system
CN120670112A
Application program optimization method and device, electronic equipment and storage medium
CN120848934A
Cited By
SIMD architecture-oriented neural network processor intra-core scheduling method and system
CN121833052A
