On-demand loading method based on React framework and storage medium
By adopting on-demand loading methods and modern web technologies in the React framework, the problems of performance bottlenecks and resource waste in the initial loading process of traditional web applications are solved, and faster and smoother user experience and efficient resource utilization are achieved.
Patent Information
- Application Number
- CN202411810489.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-12-10
- Publication Date
- 2025-04-25
AI Technical Summary
Traditional web applications have performance bottlenecks and resource waste problems during the initial loading process, resulting in increased user waiting time and wasted network bandwidth and device resources.
Adopt the on-demand loading method based on the React framework, and through intelligent binding of page resources and routing components, using modern web technologies such as CDN, HTTP caching, preloading, asynchronous loading, Service Worker and lazy loading, we optimize resource loading methods and dynamic dependency management.
It significantly shortens page loading time, improves resource utilization, reduces unnecessary bandwidth consumption and device resource consumption, and improves user experience and system performance.
Smart Images

Figure CN119883400A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of Web application programs, in particular to the technical field of optimizing resource loading modes and dynamic dependency management, and in particular to an on-demand loading method and storage medium based on a React framework. Background Art
[0002] In the complex ecosystem of web development, lazy loading has become a key technology for optimizing the initial loading experience. This strategy focuses on loading resources only when necessary, such as when the content that the user is about to view or interact with requires a specific script, image, or component. Vue Router's lazy loading mechanism is a good example. It implements the on-demand introduction of routing components through an asynchronous component loading mechanism, greatly reducing the burden of loading the homepage and speeding up the initial presentation of the page.
[0003] Server-Side Rendering (SSR) and Client-Side Rendering (CSR) represent two different philosophies of page construction. SSR significantly shortens the first screen loading time and improves the immediacy of user experience by generating a complete HTML page on the server side and then transmitting it to the browser. However, this advantage comes with higher server computing pressure and potential response delays. In contrast, CSR dynamically builds pages on the client side, which sacrifices the initial loading speed but gives the page higher interactive flexibility and dynamism. The choice between the two should be based on a comprehensive consideration of user experience, server resources and maintenance costs.
[0004] To further accelerate resource loading, modern Web applications widely use multi-layer caching strategies, including but not limited to browser caching, Service Workers, and Content Delivery Network (CDN) caching. These technologies effectively reduce the burden of network requests and round-trip time by storing frequently accessed or static resources, especially in improving user experience in high-latency network environments. Service Workers set new standards for the availability and performance of Web applications by providing offline access capabilities and intelligent resource update mechanisms.
[0005] However, this traditional "full loading mode", that is, downloading all the resources required for the entire application at one time, simplifies the implementation logic, but exposes significant limitations in practice. It not only leads to lengthy loading times and increases users' impatience, but also wastes precious network bandwidth and device resources due to excessive preloading of resources. Especially for heavy applications containing a large amount of JavaScript and CSS, the browser's rendering blocking phenomenon is more serious, which directly delays the visual feedback of the page and aggravates the white screen time. This problem is more prominent on mobile devices. Limited processing power and network conditions make the download and parsing of large-volume resources a major obstacle to user experience.
[0006] To this end, the present invention proposes an on-demand loading method and storage medium based on a React framework. Summary of the invention
[0007] In view of this, the present invention hopes to provide an on-demand loading method and storage medium based on the React framework to solve or alleviate the technical problems existing in the prior art, that is, how to solve the performance bottleneck and resource waste problems faced by traditional Web applications during the initial loading process, and at least provide a beneficial option for this; the technical solution of the present invention is implemented as follows:
[0008] 1. Overview:
[0009] This paper proposes an innovative on-demand loading solution based on the React framework. The core concept of this solution is dependency reuse, which intelligently binds the resources required by the page with the routing components to improve the system's response speed and resource utilization. The original intention of the design of this solution is to cope with the challenges encountered by traditional Web applications in the initial loading stage, and to achieve more efficient page rendering and better performance by optimizing resource loading methods and dynamic dependency management.
[0010] By combining the powerful features of the React framework, this solution aims to provide developers with a concise and efficient solution that enables them to better cope with the performance and resource management challenges in modern web application development.
[0011] (II) Technical solution:
[0012] In order to achieve the above technical objectives, the present invention needs to perform the following steps S1 to S5.
[0013] 2.1 Step S1, read the configured CDN service:
[0014] Read the validity period set by the Cache-Control directive in the HTTP header, read all dependent scripts (including frameworks, libraries, and custom components) from the CDN server, and automatically handle caching based on the HTTP response header.
[0015] At the same time, the mapping table or metadata in the back-end server or front-end routing configuration file is read to obtain the scripts and data resources representing the dependencies of each routing page or functional module.
[0016] 2.1.1 Step S100, configuration verification and reading:
[0017] Access URL, cache policy (validity period set by Cache-Control directive) and security settings, etc. And at the first request or regular verification, check the HTTP response header of the dependent script to confirm that the cache time indicated by the max-age or Expires field is effective. If yes, execute step S101; if not, trigger an abnormal response.
[0018] 2.1.2 Step S101, locate the dependent script resource location:
[0019] Compile a list of all dependent scripts, including basic frameworks, third-party libraries, and custom components. Generate a corresponding CDN and URL for each script resource in the list.
[0020] Then, read the routing configuration file (JSON format, YAML format, or configuration object directly embedded in the code) from the backend server or frontend project directory. Then analyze the mapping table or metadata in the configuration file to obtain the script file and necessary data resources corresponding to each routing page or functional module. Data resources include but are not limited to directly listed script names and data API addresses.
[0021] 2.1.3 Step S102, cache verification:
[0022] For cached resources, the browser skips re-downloading and loads directly from local, otherwise it goes to S2.
[0023] 2.2 Step S2, dependency analysis before page loading:
[0024] When a page is accessed by a user, the server analyzes the dependencies of the page based on the script and data resources read in S1 and generates a preload instruction and a prefetch instruction.
[0025] 2.2.1 Step S200, parse the URL path and query the dependency mapping table:
[0026] According to the URL requested by the user, parse out the identifier of the target page, such as the page name or ID.
[0027] Use the dependency mapping information obtained in step S1 to find all direct dependencies associated with the current page, including JavaScript, CSS style files, image resources, and necessary API data interfaces.
[0028] 2.2.2 Step S201, recursively parse the dependency tree:
[0029] For each direct dependency, check whether it has additional sub-dependencies (for example, a JS file depends on other JS libraries). If so, recursively perform dependency resolution, build a complete dependency tree structure, and then enter S202; if not, directly enter S202.
[0030] 2.2.3 Step S202, resource priority sorting:
[0031] JavaScript execution needs to come after CSS and some HTML rendering, sorting resources based on dependencies and resource types.
[0032] 2.2.4 Step S203, generating preload / prefetch instructions:
[0033] Based on the results of dependency analysis, preload and prefetch instructions are generated to tell the browser to prioritize loading of critical resources and predict resources that will be needed in the future.
[0034] 2.3 Step S3, load dependent scripts on demand:
[0035] Based on the dependencies of the page identified in S2, and the preloading instructions and pre-reading instructions in response, the server uses the asynchronous loading mechanism of the front-end framework (React's Suspense) to load necessary script files from the CDN on demand, and the browser automatically checks the local cache and obtains the HTTP cache header information it carries;
[0036] That is, let the browser check whether there is a cached copy locally. If so, reuse it directly; otherwise, pull it from the CDN.
[0037] 2.3.1 Step S300, generating dynamic loading configuration:
[0038] Based on the dependencies analyzed in S2, the server generates a configuration file for dynamically loading scripts, listing all script resources that need to be loaded asynchronously and their loading priorities.
[0039] 2.3.2 Step S301, integrating the Suspense manager:
[0040] In front-end applications, use React's Suspense component to wrap components that rely on asynchronously loaded resources. This allows React to suspend rendering of these components before the script is loaded, thus avoiding meaningless rendering or flickering.
[0041] 2.3.3 Step S302, asynchronous script request:
[0042] Use React.lazy or a custom asynchronous loading function to asynchronously request script files in the order in the configuration file. These requests carry the necessary cache validation header information, including If-Modified-Since or ETag, in order to take advantage of the browser's cache mechanism.
[0043] 2.3.4 Step S303, browser cache check:
[0044] Check whether there is a copy of the resource in the local cache, and compare the HTTP cache header information to determine whether the cache is valid. If valid, load the resource directly from the cache to form a cache copy without sending a request to the server. If not, execute step S304.
[0045] 2.3.5 Step S304, conditional request processing:
[0046] If the required resource is not in the cache or has expired, the browser sends a request to the CDN to obtain the latest resource. The CDN decides whether to return a 304 response or re-provide the resource based on the cache header information in the request to form a cache copy.
[0047] 2.3.6 Step S305, module analysis and execution:
[0048] After successfully obtaining the script, the React front-end framework is responsible for parsing the loaded module and executing the code in it to make the related components available. The Suspense component is then unsuspended and continues to render components that depend on these scripts.
[0049] 2.4 Step S4, data pre-fetching and cache utilization:
[0050] Based on the cached copy obtained from S3, Ajax requests are used to obtain data from the server or API according to the page data requirements (user information, product list or dynamic content, etc.). Service Worker and browser cache strategies are used to cache frequently accessed data, reduce network requests, and speed up data loading.
[0051] 2.4.1 Step S400, execute cache strategy:
[0052] Set up long-term caching for frequently accessed and infrequently changing data, use the Cache API or IndexedDB to store data, and define caching strategies in Service Worker scripts.
[0053] 2.4.2 Step S401, execute Ajax data request:
[0054] Initiate a data request through Ajax. Before the request, use Service Worker to intercept the request and check whether there is a valid cache copy. If Service Worker detects that the requested data is already in the cache (and has not expired), it returns the data directly from the cache, skipping the network request to speed up the response. If not, go to S402.
[0055] 2.4.3 Step S402, execute network data acquisition:
[0056] When the requested data is not in the cache or the cache has expired, the Service Worker allows the request to go through, gets the latest data from the server, and updates the cached copy.
[0057] 2.4.3 Step S403, perform data pre-fetching:
[0058] Use Service Worker for preloading and precaching, analyze user behavior patterns or page logic, and predict data that may be needed.
[0059] Use the Cache-then-Network strategy to update data in the background while using the cache, ensuring that users can see the latest content while enjoying a fast loading experience.
[0060] 2.5 Step S5, rendering and lazy loading other resources:
[0061] Page rendering starts after the key dependent scripts and data are loaded.
[0062] At the same time, non-critical resources (such as pictures or videos) are lazily loaded on demand according to page scrolling or other triggering conditions to maintain a fast response for first screen loading.
[0063] 2.5.1 Step S500, initialize page rendering and lazy loading listener:
[0064] Trigger React's rendering process to build and display the basic structure and content of the page for fast first screen load. Activate lazy load listeners set in the page DOM for non-critical resources (such as images, videos, and additional components).
[0065] 2.5.2 Step S501, resource visibility detection:
[0066] Use the Intersection Observer API to monitor when non-critical resource elements enter or approach the viewport. Once the preset conditions (such as the element visible ratio threshold) are met, trigger the resource loading.
[0067] 2.5.3 Step S502, asynchronously loading non-critical resources:
[0068] For non-critical resources that enter the visible area, asynchronous loading requests are initiated. This includes dynamic creation , <video>Tag or use Ajax / Fetch to request data.
[0069] 2.5.4 Step S503, resource loading status management:
[0070] Use placeholders or skeleton screens to keep the page layout stable, while providing loading progress prompts or animations to enhance the user experience.
[0071] (III) Mechanism for solving technical problems:
[0072] 3.4 Intelligent Cache Utilization and Verification:
[0073] By reading the HTTP header Cache-Control directive of the CDN service, the cache is automatically processed to ensure effective reuse of resources. The configuration verification step ensures the correct implementation of the script-dependent cache strategy and reduces unnecessary network requests. Analyze page dependencies, generate preload and prefetch instructions, prioritize loading of key resources, predict and request resources that may be needed in the future in advance, greatly improving the loading speed and responsiveness of the page.
[0074] 3.2 On-demand loading and asynchronous processing:
[0075] React's Suspense mechanism and dynamic loading configuration enable components to load corresponding scripts only when they are really needed, reducing the burden of initial loading and improving user experience. The asynchronous loading strategy is closely integrated with the browser cache mechanism to further optimize the resource acquisition process. Service Worker and browser cache strategies are used to cache frequently accessed data to reduce repeated network requests. By analyzing the pre-fetching strategy, data is loaded predictively to ensure the immediate availability of data while ensuring the freshness of the data.
[0076] 3.3 Lazy loading of non-critical resources:
[0077] Non-critical resources such as images and videos are loaded only when the resources are visible or nearly visible, which reduces the first screen loading time and improves the user experience. Intelligent loading is triggered through the Intersection Observer API, combined with loading state management, to ensure a smooth loading process and optimized user perception.
[0078] In summary, the technical solution of the present invention adopts targeted loading strategies for different types of resources and data by comprehensively using modern Web technologies such as CDN, HTTP caching, preloading, asynchronous loading, Service Worker and lazy loading, which not only shortens the page loading time, but also improves the efficiency of resource utilization and reduces unnecessary bandwidth consumption, thereby solving the performance bottleneck and resource waste problems of traditional Web applications in the initial loading process, and providing a faster and smoother user experience.
[0079] (IV) Compared with the prior art, the beneficial effects of the present invention are:
[0080] (1) Improve page loading speed: The present invention ensures that key resources can be loaded quickly through cache control, preloading and prefetching strategies, reducing the user's waiting time. In particular, the on-demand loading and lazy loading mechanisms ensure that the first screen content of the page is presented quickly, improving the user experience.
[0081] (2) Optimize resource utilization: The present invention intelligently manages resource cache, avoids unnecessary repeated downloads, reduces server bandwidth consumption and client storage pressure. Through dynamic loading configuration and Service Worker cache strategy, effective resource reuse is achieved, improving overall resource utilization efficiency.
[0082] (3) Enhanced user experience: The present invention manages the asynchronous loading process through the Suspense component, avoiding meaningless rendering or interface flickering, making the page transition smoother and more natural. Lazy loading of non-critical resources such as pictures and videos ensures the first screen loading speed while maintaining the richness of multimedia content, thereby improving user satisfaction. The data pre-fetching strategy and Cache-then-Network strategy ensure that users can quickly obtain the latest data content, while using the cache to reduce latency, achieving a balance between data immediacy and efficiency.
[0083] (4) Reduce server load and green and low carbon: Since a large number of static resources and some dynamic data are provided by CDN and browser cache, the technical solution of the present invention indirectly reduces the pressure of the server directly processing requests, especially in high-concurrency scenarios, which can improve the stability and scalability of the system. By reducing unnecessary network transmission and improving loading efficiency, the energy consumption of the data center is indirectly reduced, which is in line with the trend of green IT. BRIEF DESCRIPTION OF THE DRAWINGS
[0084] In order to more clearly illustrate the embodiments of the present application or the technical solutions in the prior art, the drawings required for use in the embodiments or technical descriptions will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present application. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative work.
[0085] Figure 1 It is a schematic diagram of the method flow of the present invention. DETAILED DESCRIPTION
[0086] In order to make the above-mentioned purposes, features and advantages of the present invention more obvious and easy to understand, the specific implementation methods of the present invention are described in detail below in conjunction with the accompanying drawings. In the following description, many specific details are set forth to facilitate a full understanding of the present invention. However, the present invention can be implemented in many other ways different from those described herein, and those skilled in the art can make similar improvements without violating the connotation of the present invention. Therefore, the present invention is not limited to the specific embodiments disclosed below;
[0087] It should be noted that the various embodiments in this specification are described in a progressive manner, and each embodiment focuses on the differences from other embodiments, and the same or similar parts between the various embodiments can be referred to each other. For the device disclosed in the embodiment, since it corresponds to the method disclosed in the embodiment, the description is relatively simple, and the relevant parts can be referred to the method part description.
[0088] Embodiment 1: Figure 1 As shown, this embodiment discloses an on-demand loading method based on a React framework, which includes the following steps S1 to S5.
[0089] In this embodiment, regarding step S1, the configured CDN service is read: When the browser requests a resource, the Cache-Control directive in the HTTP response header of the resource is checked. This directive tells the browser how long the resource should be cached (via the max-age parameter) or until it expires (via the Expires header). With this information, the browser can determine whether it needs to re-request the resource or directly use the locally cached copy, thereby reducing unnecessary network communication.
[0090] All required scripts, including the React framework itself, third-party libraries (Redux, React Router, etc.), and project-specific custom components, are loaded from CDN servers. CDN (Content Distribution Network) accelerates the distribution of content through geographically distributed servers, reduces user-to-server latency, and further improves loading speed. In addition to loading scripts directly from CDN, the system also reads routing configuration files from the backend server or front-end project. This configuration file can exist in the form of JSON, YAML, or hard-coded in the code, and contains the mapping relationship between each page or functional module and its required scripts and data resources.
[0091] Specifically, step S100, configuration verification and reading: During the first load or periodic verification, the system checks the HTTP response header of the dependent script to ensure that the Cache-Control setting is correct and valid. If the verification passes, it continues to the next step; if it is found that the configuration is incorrect or the cache policy is invalid, an abnormal response is triggered, redirecting to the correct configuration or prompting an error message.
[0092] Specifically, step S101, locating dependent script resources: generating a detailed list of dependent scripts, including basic frameworks, third-party libraries and custom components, and assigning each script its URL on the CDN. This step ensures that the system clearly knows all the resources that need to be loaded and their sources.
[0093] Then, read the routing configuration file (JSON format, YAML format, or configuration object directly embedded in the code) from the backend server or frontend project directory. Then analyze the mapping table or metadata in the configuration file to obtain the script file and necessary data resources corresponding to each routing page or functional module. Data resources include but are not limited to directly listed script names and data API addresses.
[0094] Specifically, step S102, cache verification: the browser uses the Cache-Control directive mentioned above to automatically verify whether the locally cached resources are still valid. If the resource has been cached and has not expired, it is directly loaded from the local without requesting the server again, which greatly improves the page loading speed. For uncached or expired resources, re-download them according to the normal process. Otherwise, enter S2.
[0095] It is understandable that by utilizing CDN to accelerate resource distribution and intelligent cache management, the loading time of the page for the first time and subsequent visits is significantly reduced, improving the user experience. Unnecessary network traffic is reduced because most resources can reuse local caches, reducing server bandwidth consumption and client power consumption. Even in the case of unstable network or high server load, the local cache can still provide the necessary resources to ensure that the basic functions of the application are not affected. The centralized routing configuration file makes it simple and direct to add, modify or delete page dependencies, making it easy to maintain and iterate projects.
[0096] Furthermore, the Java framework program of step S1 (in the technology stack, Spring Boot is the main framework of the application. OkHttp is to initiate HTTP requests to obtain CDN resources and verify cache. Jackson is to parse the routing configuration file in JSON format. Spring Configuration Properties is used to read the application configuration) is as follows:
[0097] (1) First, define a configuration class to read the CDN and routing configuration information in application.yml or application.properties:
[0098] @Configuration
[0099] @ConfigurationProperties(prefix="cdn")
[0100] public class CdnConfig{
[0101] private String baseUrl;
[0102] }
[0103] @Configuration
[0104] @ConfigurationProperties(prefix="routing")
[0105] public class RoutingConfig{
[0106] private Map<String,List <string>>pageToScriptsMap;
[0107] }
[0108] (2) Then, create a service class to handle the loading of dependency scripts and parsing of routing configuration:
[0109]
[0110]
[0111] Among them, through Spring's @ConfigurationProperties annotation, the cdn and routing configuration in the configuration file are automatically mapped to Java objects, which facilitates subsequent operations.
[0112] The ResourceLoaderService service class is responsible for loading the corresponding script according to the routing request. It constructs a complete CDN URL and initiates an HTTP request through OkHttp. By analyzing the Cache-Control in the HTTP response header, the server can indirectly understand and influence the caching behavior of resources. For example, the server can tell the browser the maximum caching time of the resource by setting an appropriate max-age.
[0113] In this embodiment, regarding step S2, dependency analysis before page loading: when a page is accessed by a user, based on the script and data resources read in S1, the server analyzes the dependency of the page and generates preloading instructions and prefetching instructions.
[0114] Specifically, step S200, parse the URL path and query the dependency mapping table: When a user requests a page, the back-end server or front-end routing system first parses the URL path and extracts the page identifier (such as the page name or ID). Using the dependency mapping table established or updated in step S1 (stored in a database, memory or static file), query all directly related resources according to the page identifier. These resources include but are not limited to JavaScript files, CSS style files, pictures and other static resources, as well as endpoint information of the API data interface.
[0115] It is understandable that by pre-maintaining the dependency mapping, dynamic analysis of resource dependencies is avoided every time a page is requested, thereby reducing server burden and network latency. Directly locating resources based on page identifiers ensures that the exact set of resources required by the page is loaded, avoiding unnecessary resource loading.
[0116] Specifically, step S201 recursively parses the dependency tree: for each direct dependency, check whether it has additional sub-dependencies (for example, a JS file depends on other JS libraries). If so, recursively perform dependency parsing, build a complete dependency tree structure, and then enter S202; if not, directly enter S202.
[0117] Specifically, step S202, resource priority sorting: sorting according to resource types and dependencies between them.
[0118] For example, CSS and necessary immediately executed JS scripts have higher priority because they directly affect the initial rendering of the page. Non-blocking resources such as images and JS scripts that can be loaded lazily are ranked later. The Topological Sorting algorithm can be used to ensure that there is no circular dependency and arrange the loading order reasonably.
[0119] Specifically, step S203, generating preload / prefetch instructions: generating according to the sorted resource list<linkrel="preload"> and <link rel="prefetch"> Tags are used to instruct the browser to load key resources in advance and predict resources that may be needed in the future. These instructions can be embedded directly in the HTML head through server-side rendering (SSR) or dynamically inserted through client-side JavaScript.
[0120] It is understandable that for critical path resources, such as JS and CSS required for first screen rendering, preloading can ensure that these resources are downloaded by the browser as soon as possible, without waiting for HTML to be parsed before initiating a request. For non-critical resources that users are expected to access, such as resources on subsequent pages, prefetching can utilize the user's idle bandwidth to download in advance without affecting the loading of the current page, thereby speeding up the access speed of subsequent pages. By actively guiding the browser's behavior and loading resources on demand and predictably, network waiting time is reduced, and the overall page loading smoothness and responsiveness are improved, especially in slow network environments.
[0121] Furthermore, the Java architecture program of step S2 is as follows:
[0122] import java.util.*;
[0123] class Resource{
[0124] String name;
[0125] ResourceType type;
[0126] List <resource>dependencies;
[0127] }
[0128]
[0129]
[0130] }));
[0131] return resourcesToLoad;
[0132] }
[0133] public static void main(String[]args){
[0134] / / Initialize dependency mapping table
[0135] Map <String,List <resource>>exampleMap=new HashMap<>();
[0136] / / Fill in dependency mapping table data
[0137] DependencyAnalyzer analyzer=new DependencyAnalyzer(exampleMap);
[0138] List <resource>dependencies=
[0139] analyzer.analyzeDependencies("page1");
[0140] }
[0141] }
[0142] In the above program, a depth-first traversal (DFS) is implemented through a stack, starting from the initial page resource, and recursively traversing all dependent resources until there are no new dependencies. This ensures that each resource and its sub-dependencies are accessed and only accessed once, avoiding the problem of circular dependencies. After collecting all dependent resources, a Comparator is used to sort the resource list to ensure that resources that affect the initial rendering of the page, such as CSS and JS, are loaded first.
[0143] In this embodiment, regarding step S3, dependent scripts are loaded on demand: based on the dependency relationship of the page identified in S2, and the responded preloading instruction and pre-reading instruction, the server uses the asynchronous loading mechanism of the front-end framework (React's Suspense) to load necessary script files from the CDN on demand, and the browser automatically checks the local cache and obtains the HTTP cache header information it carries;
[0144] That is, let the browser check whether there is a cached copy locally. If so, reuse it directly; otherwise, pull it from the CDN.
[0145] Specifically, step S300 generates a dynamic loading configuration: based on the dependency relationship analyzed in S2, the server generates a configuration file for dynamically loading scripts, listing all script resources that need to be asynchronously loaded and their loading priorities. This ensures that the most core resources that are most critical to the initial rendering of the page can be loaded first, thereby speeding up the time it takes for users to see the first screen content.
[0146] Specifically, step S301, integrating the Suspense manager: React's Suspense component is the core of asynchronous loading management, which allows developers to specify which parts of the rendering in the component tree should wait for specific asynchronous operations to complete. When the resources that the component wrapped in Suspense depends on have not been loaded, React will suspend the rendering of this part until the resources are loaded, thereby avoiding the interface flickering or white screen with no content.
[0147] By suspending rendering until resources are ready, Suspense improves the smoothness of the user experience, allowing users to perceive a smooth transition rather than sudden content changes.
[0148] Specifically, step S302, asynchronous script request: using React.lazy or a custom asynchronous loading function, initiate requests according to the configuration file sequence. These requests carry HTTP cache validation header information, allowing the browser and server to efficiently negotiate cache usage and reduce unnecessary network transmission. By utilizing the cache mechanism, the amount of data transmission is greatly reduced, the resource loading speed is accelerated, the server pressure and user data cost are reduced, especially for users who visit repeatedly, the experience is more significant.
[0149] Specifically, step S303, browser cache check: before sending the actual request, the browser first checks whether there is a cached version of the resource locally, and determines the validity of the cache based on the HTTP cache header information (such as If-Modified-Since, ETag). This step ensures that new resources are obtained from the server only when absolutely necessary. It greatly improves the loading speed because loading resources from the local cache is much faster than network requests. In addition, it reduces bandwidth consumption, is particularly friendly to mobile devices, and extends battery life.
[0150] If it is valid, the resource is directly loaded from the cache to form a cache copy without sending a request to the server. If not, execute step S304.
[0151] Specifically, step S304, conditional request processing: when confirming that the cache is invalid or missing, the browser initiates a conditional GET request to the CDN, and the request header contains the resource information downloaded last time. Based on this information, the CDN decides whether to return a "not modified" (304 Not Modified) response, instructing the browser to use the cached copy, or send new resource content. This reduces the need to completely re-download resources, further saves network resources and time, and also reduces the burden on the CDN and server.
[0152] Specifically, step S305, module parsing and execution: Once the script is successfully downloaded, the React framework is responsible for parsing these modules and executing the internal JavaScript code, so that the components that rely on these scripts become renderable. Subsequently, the previously suspended Suspense component is released and the normal rendering process continues. This final step ensures the dynamics and interactivity of the application. Users can start interacting with the loaded components, and the overall experience is seamless and instant. At the same time, this dynamic loading mechanism helps to keep the application lightweight, loading resources only when they are really needed, and optimizing memory usage and performance.
[0153] Furthermore, the Java architecture program of step S3 is as follows, which builds a server-side rendering (SSR) or static site generation (SSG) system to analyze dependencies, generate configurations, and work with the front-end React application:
[0154] (1) Analyze dependencies and generate dynamic loading configuration: A server-side module is responsible for analyzing the React components corresponding to the route and the modules it depends on. Parse the front-end Webpack package list or other metadata files. Based on the analysis results, the Java backend generates a dynamic loading configuration file in JSON format, which includes a list of scripts that need to be loaded for each route or component and their priority. This configuration file can be provided to the front end as part of the API response:
[0155] @Service
[0156]
[0157] (2) Front-end Suspense configuration and asynchronous loading request (S301-S302): The Java back-end needs to provide an API to support dynamic loading logic, for example, to provide an API interface through which the front-end can obtain the dynamic loading configuration:
[0158]
[0159] public ResponseEntity <loadconfig>getLoadConfig(@PathVariable Stringroute){
[0160] LoadConfig config=
[0161] analysisService.generateLoadConfig(route);
[0162] return ResponseEntity.ok(config);
[0163] }
[0164] }
[0165] In this embodiment, regarding step S4, data pre-fetching and cache utilization: according to the cache copy obtained in S3, according to the page data requirements (user information, product list or dynamic content, etc.), use Ajax request to obtain data from the server or API. Use Service Worker and browser cache strategy to cache frequently accessed data, reduce network requests, and speed up data loading.
[0166] Specifically, step S400 executes the cache strategy: for data that is not frequently changed and frequently accessed, use browser storage technologies such as CacheAPI or IndexedDB to persist the cache. Cache API is suitable for responses to HTTP requests, while IndexedDB is suitable for structured data storage. The logic is implemented in the Service Worker script to distinguish the freshness and importance of the data, and set different cache validity periods for different types of resources (such as the max-age instruction).
[0167] It is understandable that Service Worker acts as a proxy between the browser and the network, and can monitor, intercept and modify network requests. It runs in the background, independent of the main thread, so it can manage the cache efficiently. By setting a long-term validity period, it ensures that commonly used resources do not need to be re-downloaded frequently, reducing bandwidth consumption and loading time. When users visit repeatedly, data is read directly from the cache and loaded almost instantly, improving the user experience.
[0168] Specifically, step S401, execute Ajax data request: before initiating Ajax request, Service Worker will check whether the request hits the cache. When using fetch() API, you can control whether to use cache first through cache option or custom logic.
[0169] It is understandable that Service Worker intercepts Ajax requests, compares the requested URL with the cache entry, and decides whether to directly provide the cached data. If the cache hits, it responds directly, avoiding network round-trip delays. As a result, the loading time perceived by users is significantly shortened, improving the smoothness of interaction and reducing the pressure on the server to process requests.
[0170] Specifically, step S402 executes network data acquisition: when the data is not in the cache or has expired, the request is allowed to continue to be sent to the server through the Service Worker. After acquiring the data, the cache managed by the Service Worker is updated to ensure that the next request can be directly hit. It is ensured that the user obtains the latest data, even if the first load may be slow, but the timeliness of the overall data is improved.
[0171] Specifically, step S403 performs data pre-fetching: using the pre-loading capability of Service Worker, predictively load the data that may be needed based on user behavior analysis or page structure logic. Implement the Cache-then-Network strategy, first provide data from the cache, and update the cache in the background to ensure the immediacy and freshness of the data.
[0172] Understandably, without affecting the current user experience, the background quietly updates the data to ensure that the latest data is available for the next visit. Users can hardly feel the data loading process during browsing, which improves the smoothness of continuous operations.
[0173] Furthermore, the Java architecture program of step S4 is as follows:
[0174] (1) Backend data service (Java):
[0175] @RestController
[0176] @RequestMapping(" / api / data")
[0177] public class DataController {
[0178] @GetMapping(" / {resourceId}")
[0179] public ResponseEntity <dataresponse>getData(@PathVariable StringresourceId){
[0180]
[0181] (2) Service Worker registration and configuration (front-end JavaScript): The backend can provide default settings for the cache strategy:
[0182]
[0183]
[0184] (3) Client data pre-fetching and cache utilization logic (front-end JavaScript): Use the characteristics of Service Worker to pre-fetch data and cache utilization:
[0185]
[0186] Providing a stable data interface in the above program is the data source of the entire architecture and supports the acquisition and update of dynamic data. Service Worker registration and configuration As a proxy layer between the browser and the network, Service Worker can intercept network requests to achieve offline access, cache strategy execution, and data prefetching. By preloading static resources in the installation event and checking and utilizing the cache in the fetch event, data loading performance is optimized. The front-end application predicts the data that may be needed in the future based on user behavior or page logic, and initiates a request in advance through the Service Worker to preload the data into the cache. When the user actually needs this data, it can be quickly obtained directly from the cache, which significantly improves the user experience.
[0187] In this embodiment, regarding step S5, rendering and lazy loading other resources: page rendering starts after the key dependent scripts and data are loaded. At the same time, non-critical resources (such as pictures or videos) are lazy loaded on demand according to page scrolling or other triggering conditions to maintain a fast response of the first screen loading.
[0188] Specifically, step S500, initialize page rendering and lazy loading listener: At the appropriate time in the React component life cycle (such as componentDidMount or useEffect using React Hooks), start the first rendering of the page. At this time, only the necessary structure and content are rendered, and for non-critical resources, placeholders (such as gray blocks or default images) can be used instead, and Intersection Observer listeners are registered. The listener is responsible for tracking when these resource elements approach or enter the browser viewport.
[0189] Specifically, step S501, resource visibility detection: use the built-in Intersection Observer API of the browser, which is a high-performance method for asynchronously monitoring the intersection changes of the target element with the viewport or its ancestor elements. The developer defines a callback function, which is triggered when the observed target element meets the preset conditions (such as at least 20% of the area is visible). At the same time, an Observer instance is created for each element that needs to be lazy loaded, and the visibility threshold is configured. When the element meets the conditions, the next operation is triggered.
[0190] Specifically, step S502, asynchronously loading non-critical resources: once the listener is triggered, by dynamically creating a DOM element (such as , <video>Tag) and set its src attribute, or use fetch or XMLHttpRequest (Ajax) to asynchronously request data. In this way, resources are loaded only when they are really needed, reducing unnecessary network requests.
[0191] Specifically, step S503, resource loading status management: during resource loading, maintain the page layout stable, use skeleton screens or placeholders to maintain the expected visual structure, and display the loading progress bar or animation to give users instant feedback, avoid "white screen" or layout jump phenomenon, and improve perceived performance.
[0192] Preferably, the loading state (such as loading, loaded, error) can be maintained for each lazy-loaded resource, and the displayed content can be switched through CSS or React state management, transitioning from placeholders to actual content or error prompts.
[0193] It is understandable that by reducing the amount of data transferred when the page is first loaded, the first screen rendering speed is accelerated, the user waiting time is reduced, and the usability and attractiveness of the application are improved. On-demand loading ensures that network bandwidth and computing resources are focused on the content that the current user is most concerned about, avoiding unnecessary resource preloading. Through loading progress prompts and stable layouts, users can clearly perceive that the page content is loading, reducing uncertainty and potential frustration, and enhancing the overall interaction fluency.
[0194] All the above embodiments only express the implementation methods of the relevant practical applications of the present invention, and the descriptions thereof are relatively specific and detailed, but they cannot be understood as limiting the scope of the invention patent. It should be pointed out that, for ordinary technicians in this field, several variations and improvements can be made without departing from the concept of the present invention, which all belong to the protection scope of the present invention. Therefore, the protection scope of the patent of the present invention shall be based on the attached claims.
[0195] For those skilled in the art, it can be further appreciated that the units and algorithm steps of each example described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of the two. In order to clearly illustrate the interchangeability of hardware and software, the composition and steps of each example have been generally described in the above description according to function. Whether these functions are performed in hardware or software depends on the specific application and design constraints of the technical solution. Professional and technical personnel can use different methods to implement the described functions for each specific application, but such implementation should not be considered to be beyond the scope of the present invention.
[0196] At the same time, those skilled in the art can understand that all or part of the processes in all the above-mentioned embodiments can be completed by instructing the relevant hardware through a computer program, and the computer program can be stored in a non-volatile computer-readable storage medium. When the computer program is executed, it can include the processes of the embodiments of the above-mentioned methods. Among them, any reference to memory, storage, database or other media provided in this application and used in the embodiments can include non-volatile and / or volatile memory. Non-volatile memory can include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM) or flash memory. Volatile memory can include random access memory (RAM) or external cache memory. As an illustration and not limitation, RAM is available in many forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), double-speed data rate SDRAM (SSRSDRAM), enhanced SDRAM (ESDRAM), synchronous link (Synchlink) DRAM (SLDRAM), memory bus (Rambus) direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM).< / video> < / dataresponse> < / loadconfig> < / resource> < / resource> < / resource> < / string> < / video>
Claims
1. A method for on-demand loading based on the React framework, characterized in that: The steps include: S1, read the configured CDN service: read the validity period set by the Cache-Control directive in the HTTP header, read all dependent scripts from the CDN server, and automatically process the cache based on the HTTP response header; S2, dependency analysis before page loading: When a page is accessed by a user, based on the script and data resources read in S1, the server analyzes the dependency of the page and generates preloading instructions and prefetching instructions; S3, load dependent scripts on demand: let the browser check whether there is a cached copy locally. If so, reuse it directly, otherwise pull it from the CDN; S4, data pre-fetching and caching uses the cache copy obtained according to S3 to obtain data from the server or API using Ajax requests according to page data requirements; S5, rendering and lazy loading of other resources. After the key dependent scripts and data are loaded, page rendering begins.
2. The on-demand loading method according to claim 1, characterized in that: In the S1, it also includes reading a mapping table or metadata in a backend server or a frontend routing configuration file to obtain scripts and data resources representing the dependency relationship of each routing page or functional module.
3. The on-demand loading method according to claim 2, characterized in that: The implementation steps of S1 include: S100, access URL, cache policy, and security settings; S101, sort out a list of all dependent scripts, and generate a corresponding CDN and URL for each script resource in the list; S102, cache verification: For cached resources, the browser skips re-downloading and directly loads from the local, otherwise it goes to step S2.
4. The on-demand loading method according to claim 1, characterized in that: The implementation steps of S2 include: S200, parsing the identifier of the target page according to the URL requested by the user; S201, recursively parse the dependency tree: for each direct dependency, check whether it has additional sub-dependencies. If so, recursively perform dependency parsing, build a complete dependency tree structure, and then enter S202; if not, directly enter S202; S202, JavaScript execution needs to sort resources according to dependencies and resource types after CSS and some HTML rendering S203: Generate a preload instruction and a prefetch instruction based on the result of the dependency analysis.
5. The on-demand loading method according to claim 1, characterized in that: In S3, based on the dependencies of the page identified in S2 and the responded preloading instructions and pre-reading instructions, the server utilizes the asynchronous loading mechanism of the front-end framework to load necessary script files from the CDN on demand, and the browser automatically checks the local cache and obtains the HTTP cache header information it carries.
6. The on-demand loading method according to claim 5, characterized in that: The implementation steps of S3 include: S300, based on the dependency relationship analyzed in S2, the server generates a configuration file for dynamically loading scripts, listing all script resources that need to be asynchronously loaded and their loading priorities; S301, use React's Suspense component to wrap components that rely on asynchronously loaded resources; S302, asynchronously requesting script files in the order in the configuration file; S303, check whether there is a copy of the resource in the local cache, and compare the HTTP cache header information to determine whether the cache is valid; if valid, directly load the resource from the cache to form a cache copy without sending a request to the server; if not, execute step S304; S304, the browser sends a request to the CDN to obtain the latest resources; S305, the React front-end framework is responsible for parsing the loaded modules and executing the codes therein to make the related components available.
7. The on-demand loading method according to claim 6, characterized in that: In S305, the Suspense component should unsuspend and continue to render components that depend on these scripts.
8. The on-demand loading method according to claim 1, characterized in that: The implementation steps of S4 include: S400, use Cache API or IndexedDB to store data; S401, initiate data request through Ajax; S402, when the requested data is not in the cache or the cache has expired, the Service Worker allows the request to pass, obtains the latest data from the server, and updates the cached copy; S403, use Service Worker for preloading and precaching.
9. The on-demand loading method according to claim 8, characterized in that: In S401, before the request, the Service Worker is used to intercept the request and check whether there is a valid cache copy; If the Service Worker detects that the requested data is already in the cache, it returns the data directly from the cache and skips the network request; if not, it goes to S402.
10. A storage medium, characterized in that: The storage medium stores program instructions that can implement the on-demand loading method as described in any one of claims 1-9.
Citation Information
Cited By
Supply chain front-end architecture method for multi-industry dynamic switching and routing adaptation
CN120342946A
Multi-industry dynamic switching and routing adaptation supply chain front-end architecture method
CN120342946B
Streaming on-demand loading WEB end PDF document preview method and processing terminal
CN120524055A
Document component design period and operation period micro-front-end extension method and device
CN120723336A
Page loading method and device, electronic equipment and storage medium
CN121614210A