Page loading speed comprehensive optimization method and system based on React framework
By integrating code segmentation, server-side rendering, static resource optimization, data prefetching and caching mechanisms in React applications, the problem of slow page loading speed is solved, and the page loading speed is significantly improved and the user experience is improved.
Patent Information
- Application Number
- CN202510014917.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-01-06
- Publication Date
- 2025-02-11
- Estimated Expiration
- Not applicable · inactive patent
AI Technical Summary
Existing React applications have bottlenecks in page loading speed, especially when dealing with large amounts of data and complex interactions, page loading is slow, affecting the user experience.
By deeply integrating code segmentation, server-side rendering, static resource optimization, data prefetching and caching mechanisms, a comprehensive and efficient page loading speed optimization system is built. Specific measures include using React.lazy and Suspense for code segmentation, combining Next.js for server rendering, using Webpack for static resource compression and merging, prefetching data based on the life cycle hook mechanism of React components, and through browsers and services. Side cache reduces duplicate resource acquisition requests.
Significantly shorten the overall loading time of the page, improve user experience, meet the needs of modern Internet applications for fast and smooth loading of React pages, and promote substantial progress in performance optimization of front-end development.
Smart Images

Figure CN119415793A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of front-end development, and in particular relates to a method and system for comprehensive optimization of page loading speed based on a React framework. Background Art
[0002] In the field of front-end development, with the increasing richness of Web application functions and the continuous growth of data volume, users' expectations for page loading speed are also getting higher and higher. React framework has been widely used in building complex user interfaces due to its efficient component development model and virtual DOM technology. However, existing React applications still have certain bottlenecks in page loading speed, especially when dealing with large amounts of data and complex interactions. The problem of slow page loading is more prominent, which seriously affects the user experience.
[0003] The existing related technical solutions mainly include the following, but each has certain limitations: Code splitting technology: For example, using React.lazy and Suspense for code splitting, the principle is to split the application code into multiple smaller modules and load them on demand. However, in actual applications, this method often fails to fully consider the dependencies between modules and the overall architecture optimization, resulting in that although some codes are delayed loading, the effect of reducing the initial loading time is not ideal, and there is still a lot of unnecessary code loaded in the initial stage, which affects the fast presentation of the page.
[0004] Server-side rendering (SSR) technology: For example, server-side rendering is implemented through frameworks such as Next.js, which transfers part of the rendering work originally performed on the client to the server. However, the existing solutions lack effective integration with subsequent client interaction and optimization during the server-side rendering process. The page rendered by the server may still require a lot of additional processing on the client, such as reloading scripts and styles, which fails to fundamentally reduce the rendering pressure on the client, resulting in limited improvement in the overall loading speed.
[0005] Static resource optimization technology: It is common to use Webpack for resource compression, which mainly reduces the file size by removing redundant characters and spaces in the file. However, this optimization method is mostly performed independently, and is not combined with other key optimization links such as data pre-fetching and caching mechanisms. In the actual page loading process, although the file size is reduced, due to the lack of comprehensive consideration of data acquisition timing and cache utilization, the number of HTTP requests is still high, and there is still much room for improvement in resource loading speed.
[0006] Data pre-fetching technology: Some solutions combine data pre-fetching with intelligent data management strategies, such as using GraphQL to aggregate data and obtain only necessary data, which can reduce data transmission and processing to a certain extent. However, there are deficiencies in the integration with the overall page loading process. The timing of data pre-fetching, the accuracy of pre-fetched data, and the coordination with other parts of the page need to be further optimized to better play its role in reducing user waiting time.
[0007] Caching mechanism: Some existing technologies are committed to ensuring that users get the latest content without sacrificing loading speed by implementing dynamic cache updates, cache tiering and expiration strategies. However, there is still room for improvement in cache management and utilization efficiency. For example, the cache hit rate may be low, and the synchronization between the cache and actual data updates is not timely enough, resulting in the inability to fully utilize the advantages of caching to reduce repeated requests and accelerate resource loading in some cases.
[0008] In summary, although the existing technology has made some progress in optimizing the loading speed of React pages, there is a lack of effective integration and coordinated optimization between the various technical solutions, which makes it difficult to meet the growing demand for high-performance Web applications. Therefore, there is an urgent need for a comprehensive optimization method and system that can comprehensively and systematically solve the problem of slow loading speed of React pages. Summary of the invention
[0009] In view of the fact that in the existing technologies related to the optimization of page loading speed of the React framework, there are deficiencies such as code segmentation not fully reducing the initial loading time, server-side rendering not effectively reducing the pressure of client rendering, static resource optimization not combining data pre-fetching and caching mechanisms, resulting in slow loading speed, etc., the present invention provides a comprehensive optimization method and system for page loading speed based on the React framework, which is committed to building a comprehensive and efficient optimization system through deep integration and innovation of technologies such as code segmentation, server-side rendering, static resource optimization, data pre-fetching and caching mechanisms. Work together in all aspects of page loading, accurately optimize code execution, strengthen server and client collaboration, improve resource utilization efficiency, ensure timely data acquisition and efficient cache management, thereby significantly shortening the overall page loading time, effectively improving user experience, meeting the urgent needs of modern Internet applications for fast and smooth loading of React pages, and promoting substantial progress in performance optimization in front-end development.
[0010] To achieve the above object, the technical solution adopted by the present invention is as follows: In a first aspect, the present invention provides a method for comprehensive optimization of page loading speed based on a React framework, comprising the following steps: Step S1: Code splitting operation: By using the React.lazy function and Suspense component in the React framework to perform code splitting, components can be loaded on demand to reduce the initial loading time of the application; Step S2: Server-side rendering process, combined with the Next.js framework, implements server-side rendering, moves part of the rendering work to the server to reduce client-side rendering pressure; Step S3: Static resource optimization, by using the Webpack tool to compress and merge static resources, reducing the number of HTTP requests and resource size; Step S4: Data pre-fetching strategy, based on the lifecycle hook mechanism of the React component, pre-fetches the required data before the user accesses the page to reduce the user's waiting time; Step S5: Implement the cache mechanism, using the browser cache and server cache functions to reduce repeated resource acquisition requests.
[0011] Furthermore, the step S1 specifically includes: Step S11: define a lazy loading component: use the React.lazy function of the React framework to define a lazy loading component named LazyComponent, which accepts a function that calls the import function to dynamically import components as a parameter, thereby realizing dynamic loading of components; Step S12: Wrap the lazy loading component with the Suspense component: Wrap the defined LazyComponent lazy loading component with the Suspense component, and set a React element for its fallback attribute to display a waiting prompt to the user during the loading of the lazy loading component; Step S13: Render the lazy component: Inside the Suspense component, render the LazyComponent as a child component. When the component is rendered for the first time, React will try to load the LazyComponent lazy component; before the component is loaded, the user will see the content defined in the fallback attribute.
[0012] Furthermore, the step S2 specifically includes: Step S21: Code imports React library: The code first imports React library to provide basic support for the construction of server-side rendering related components; Step S22: Define a React component: define a stateless function component named HomePage for receiving data attributes, which receives an attribute named data; the component returns an HTML structure containing a title and a paragraph; the paragraph displays the input data; Step S23: Get server-side properties: an asynchronous function named getServerSideProps, which is used to obtain data on the server side; This asynchronous function uses the fetch function to get data from the API interface. The fetch function returns a promise, which is resolved into a response object. The response object is parsed into data in JSON format. The function returns an object that contains a property called props, which is itself an object containing the data obtained from the API.
[0013] Step S24: Data transfer and page rendering: The getServerSideProps asynchronous function is executed on the server side to obtain data from the API and pass the data as attributes to the HomePage component. When a page request occurs, the server renders the HomePage component with preloaded data and sends HTML to the client. After the client receives the prerendered page, it displays the page content containing the API data.
[0014] Furthermore, the step S3 specifically includes: Step S31: Configure module export: Use the module export method of Node.js, that is, use the module.exports object to define the configuration object of Webpack, which serves as the configuration entry for Webpack to optimize static resources; Step S32: Optimization configuration: In the module.exports object, there is an optimization attribute, which is an object itself and is used to configure the optimization function of Webpack; Step S33: Code splitting settings: In the optimization object, there is a splitChunks property, which is also an object; the chunks property in the splitChunks object is set to all, indicating that Webpack will perform split optimization on all types of chunks; Step S34: Code compression: In the optimization object, the minimize attribute is set to true; Webpack's ability to compress all output code packages is enabled, including compressing the output code packages through UglifyJS or Terser plug-ins. Compression can reduce the size of the output file and improve loading speed and performance; Step S35: Performance optimization and user experience improvement: Through configuration, Webpack can manage project resources more efficiently and reduce the amount of data required for initial loading through code splitting and compression.
[0015] Furthermore, the step S4 specifically includes: Step S41: Use the useEffect hook: Use the useEffect hook function in the React component to handle the side effect operation of obtaining data from the remote API. The useEffect function accepts two parameters, one is the function that performs the data acquisition operation, and the other is the dependency array. By setting the dependency array to an empty array, ensure that the data acquisition operation is only performed once when the component is first rendered; Step S42: Define an asynchronous data acquisition function: define an asynchronous function named fetchData to perform data acquisition operations. Inside the fetchData function, use the fetch function to call an API to obtain data; the fetch function returns a promise, which provides a response object after being resolved; Step S43: Process the response and update the state: Use the await keyword to wait for the response of the fetch function, and then use the res.json method to convert the response body into JSON format data; call the setData function to update the state of the component and save the acquired data to the state; this will trigger the re-rendering of the component to display the new data; Step S44: trigger the data acquisition function: call fetchData in the side effect function of useEffect to ensure that the data is acquired immediately after the component is rendered for the first time; Step S45: Optimize user experience and performance: By obtaining data only once when the component is loaded, unnecessary network requests and resource consumption are reduced; ensure timely data updates and correct state management, and improve application responsiveness and user satisfaction.
[0016] Furthermore, the step S5 specifically includes: Step S51: Register a fetch event listener in ServiceWorker: Use the event listening mechanism of ServiceWorker to register a fetch event listener through the self.addEventListener method. The listener is triggered when the browser initiates a resource acquisition request, including one or more resource requests such as loading web pages, pictures, and CSS files; Step S52: intercepting and processing the network request: in the callback function of the fetch event, use the event.respondWith method to intercept the original network request of the browser and provide a custom response processing logic; Step S53: Check whether the requested resource exists in the cache: check whether there is a cache item matching the requested resource in the cache under the current domain through the caches.match method, which returns a Promise object; Step S54: Return cached resources or make a network request: If a matching cache item is successfully found, the cached resource is directly returned as a response to avoid repeated network requests; if no matching resource is found in the cache, fetch(event.request) is executed to initiate an actual network request to obtain the resource; Step S55: Cache newly acquired resources: For new resources successfully acquired from the network, use the caches.open method to open the cache space with the specified name, and then use the cache.put method to add the newly acquired resources to the cache. When adding the cache, you need to use the response.clone method to copy the response object, because the original response object can only be read once, and the put method and returning the response to the browser both require reading the response content; Step S56: Return a response to the browser: Finally, the resource obtained from the cache or the resource obtained from the network request and cached is returned to the browser through the event.respondWith method to complete the response to the request.
[0017] A second aspect of the present invention provides a page loading speed comprehensive optimization system based on a React framework, the system is used to implement the above method, and the system comprises: The code splitting module is configured to perform code splitting operations, specifically: Define a lazy loading component named LazyComponent through React.lazy function. This function accepts a function that calls the import function to dynamically import components as a parameter, so as to realize dynamic loading of components; Use the Suspense component to wrap the defined LazyComponent lazy loading component, and set a React element for its fallback attribute to display a waiting prompt to the user during the loading of the lazy loading component; Inside the Suspense component, render the LazyComponent as a child component. When the component is first rendered, React will try to load the LazyComponent lazy loading component. Before the component is loaded, the user will see the content defined in the fallback property. The server-side rendering module is configured to execute the server-side rendering process, specifically: The code introduces the React library to provide basic support for the construction of server-side rendering related components; A stateless function component named HomePage is defined to receive data attributes. It receives an attribute named data. The component returns an HTML structure containing a title and a paragraph. The paragraph displays the passed data. Define an asynchronous function named getServerSideProps to get data on the server side. The asynchronous function uses the fetch function to get data from the API interface. The fetch function returns a promise that resolves to a response object. The response object is parsed into JSON format. The function returns an object that contains a property named props, which is itself an object containing the data obtained from the API. The getServerSideProps asynchronous function is executed on the server side to obtain data from the API and pass the data as attributes to the HomePage component. When a page request occurs, the server renders the HomePage component with preloaded data and sends the HTML to the client. After the client receives the prerendered page, it displays the page content containing the API data. The static resource optimization module is configured to perform static resource optimization, specifically: Through the module export method of Node.js, that is, using the module.exports object to define the configuration object of Webpack, which serves as the configuration entry for Webpack to optimize static resources; In the module.exports object, there is an optimization property, which is itself an object used to configure the optimization function of Webpack; The optimization object contains a splitChunks property, which is also an object. The chunks property in the splitChunks object is set to all, indicating that Webpack will perform segmentation optimization on all types of chunks. In the optimization object, the minimize property is set to true; this enables Webpack's ability to compress all output code bundles, including compressing the output code bundles through UglifyJS or Terser plugins. Compression can reduce the size of the output file and improve loading speed and performance; Through configuration, Webpack can manage project resources more efficiently and reduce the amount of data required for initial loading through code segmentation and compression; The data pre-fetching module is configured to execute the data pre-fetching strategy, specifically: In the React component, useEffect hook function is used to handle the side effect operation of obtaining data from the remote API. The useEffect function accepts two parameters, one is the function that performs the data acquisition operation, and the other is the dependency array. By setting the dependency array to an empty array, ensure that the data acquisition operation is only performed once when the component is first rendered; Define an asynchronous function named fetchData to perform data retrieval operations. Inside the fetchData function, use the fetch function to call an API to retrieve data; the fetch function returns a promise, which provides a response object after resolution; Use the await keyword to wait for the response of the fetch function, and then use the res.json method to convert the response body into JSON format data; call the setData function to update the state of the component and save the acquired data to the state; this will trigger the re-rendering of the component and display the new data; Call fetchData in the side effect function of useEffect to ensure that the data is obtained immediately after the component is rendered for the first time; By obtaining data only once when the component is loaded, unnecessary network requests and resource consumption are reduced; timely data updates and correct state management are ensured, improving application responsiveness and user satisfaction; The cache mechanism module is configured to perform cache mechanism implementation, specifically: Using the event listening mechanism of ServiceWorker, register a fetch event listener through the self.addEventListener method. This listener is triggered when the browser initiates a resource acquisition request, including one or more resource requests such as loading web pages, images, and CSS files; In the callback function of the fetch event, use the event.respondWith method to intercept the browser's original network request and provide a custom response processing logic; Use the caches.match method to check whether there is a cache item matching the resource in the cache under the current domain. This method returns a Promise object. If a matching cache item is successfully found, the cached resource is directly returned as a response to avoid repeated network requests; if no matching resource is found in the cache, fetch(event.request) is executed to initiate an actual network request to obtain the resource; For new resources successfully obtained from the network, use the caches.open method to open the cache space with the specified name, and then use the cache.put method to add the newly obtained resources to the cache. When adding the cache, you need to use the response.clone method to copy the response object, because the original response object can only be read once, and the put method and returning the response to the browser both require reading the response content; Finally, the event.respondWith method is used to return the resources obtained from the cache or the resources obtained from the network request and cached to the browser to complete the response to the request.
[0018] The present invention adopts the above technical solution, which has at least the following beneficial effects: In terms of code segmentation, the on-demand loading of components is achieved through the effective combination of React.lazy function and Suspense component. Compared with the traditional unoptimized code loading method, it can accurately reduce the amount of unnecessary code at the initial loading, thereby significantly shortening the initial loading time of the page, allowing users to see the basic framework of the page faster, improving the user's first impression of the page and the operation response speed, and enhancing the usability of the application and the smoothness of the user experience.
[0019] In terms of server-side rendering, we use the Next.js framework to migrate some rendering work to the server. This greatly reduces the rendering burden on the client and avoids the client-side freezing caused by a large number of rendering tasks. Compared with technologies that rely solely on client-side rendering, it effectively improves the overall rendering efficiency of the page, especially when dealing with complex page structures and large amounts of data, ensuring that the page is presented to users quickly and stably, improving the performance and reliability of the application.
[0020] In the static resource optimization phase, the Webpack tool is used to compress and merge static resources. By reducing redundant data in files and merging multiple small files into larger files, not only the size of resources is reduced, the amount of data transmitted over the network is reduced, but also the number of HTTP requests is effectively reduced by optimizing the segmentation of code blocks and minimizing the output bundle. This enables the page to obtain the required resources faster during the loading process, significantly improving the page loading speed and reducing the user's waiting time. The effect is particularly prominent in application scenarios with poor network environments or more resources.
[0021] The data prefetching strategy uses the lifecycle hook mechanism of the React component to obtain data from the remote API in advance before the user accesses the page. This forward-looking data acquisition method avoids the user's pause during the operation due to waiting for data to load. Compared with applications that do not use data prefetching, it greatly reduces the user's waiting time, enables the page to quickly display the latest and relevant data content, improves the responsiveness and interactivity of the application, and enhances the user's sense of fluency and satisfaction during use.
[0022] The cache mechanism integrates the browser cache and server cache functions. When a user requests a resource, it first checks whether the corresponding resource exists in the cache. Existing resources are directly retrieved and returned from the cache, avoiding repeated network requests and saving network bandwidth and server resources. Newly acquired resources can be cached in a timely and effective manner to ensure a quick response when requested again later. Compared with technologies that lack effective cache management, this mechanism significantly improves the loading speed of resources and reduces the load pressure on the server. At the same time, it ensures that users can always obtain relatively new and fast-loading resources, improving the overall performance of the application and user experience.
[0023] In summary, the comprehensive optimization method and system for page loading speed based on the React framework of the present invention, through deep integration and optimization of various key links, comprehensively improves the loading speed and performance of React application pages, effectively solves many problems existing in the prior art, and brings users a more efficient and smoother user experience. It has important application value and broad promotion prospects in the field of front-end development. BRIEF DESCRIPTION OF THE DRAWINGS
[0024] In order to more clearly illustrate the embodiments of the present invention or the technical solutions in the prior art, the drawings required for use in the embodiments or the description of the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative work.
[0025] Figure 1 It is a flow chart of the comprehensive optimization method of page loading speed of the present invention.
[0026] Figure 2 It is a flow chart of the code segmentation operation of the present invention.
[0027] Figure 3 It is a schematic diagram of the server-side rendering steps of the present invention.
[0028] Figure 4 It is the static resource optimization flow chart of the present invention.
[0029] Figure 5It is a schematic diagram of the data pre-fetching strategy of the present invention.
[0030] Figure 6 It is a flow chart of the implementation of the cache mechanism of the present invention. DETAILED DESCRIPTION
[0031] Exemplary embodiments will be described in detail herein, examples of which are shown in the accompanying drawings. When the following description refers to the drawings, the same numbers in different drawings represent the same or similar elements unless otherwise indicated. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with the present invention. Instead, they are merely examples of devices and methods consistent with some aspects of the present invention as detailed in the appended claims.
[0032] See also Figure 1 This embodiment provides a method for optimizing page loading speed based on the React framework, comprising the following steps: Step S1: Code splitting operation: By using the React.lazy function and Suspense component in the React framework to perform code splitting, components can be loaded on demand to reduce the initial loading time of the application; Step S2: Server-side rendering process, combined with the Next.js framework, implements server-side rendering, moves part of the rendering work to the server to reduce client-side rendering pressure; Step S3: Static resource optimization, by using the Webpack tool to compress and merge static resources, reducing the number of HTTP requests and resource size; Step S4: Data pre-fetching strategy, based on the lifecycle hook mechanism of the React component, pre-fetches the required data before the user accesses the page to reduce the user's waiting time; Step S5: Implement the cache mechanism, using the browser cache and server cache functions to reduce repeated resource acquisition requests.
[0033] like Figure 2 As shown, as an implementation manner, step S1 in this embodiment specifically includes: Step S11: define a lazy loading component: use the React.lazy function of the React framework to define a lazy loading component named LazyComponent, which accepts a function that calls the import function to dynamically import components as a parameter, thereby realizing dynamic loading of components; Step S12: Wrap the lazy loading component with the Suspense component: Wrap the defined LazyComponent lazy loading component with the Suspense component, and set a React element for its fallback attribute to display a waiting prompt to the user during the loading of the lazy loading component; in this example, `fallback` is a `div` element that displays "Loading..."
[0034] Step S13: Render the lazy component: Inside the Suspense component, render the LazyComponent as a child component. When the component is rendered for the first time, React will try to load the LazyComponent lazy component. Before the component is loaded, the user will see the content defined in the fallback attribute, that is, "Loading...".
[0035] like Figure 3 As shown, as an implementation mode, the process is initiated by a user (User), and the user sends a "Request Page" operation to a browser (Browser) through an operation.
[0036] After receiving the user's request, the browser sends a "Request Data" operation to the server. This step indicates that the browser needs to obtain data from the server to render the page.
[0037] After receiving the data request from the browser, the server processes the data and renders the page, and finally "returns the rendered HTML" to the browser. This step reflects the core operation of server-side rendering, that is, the server renders a complete HTML page based on the requested data.
[0038] After the browser receives the rendered HTML returned by the server, it performs the "DisplayPage" operation to present the page to the user.
[0039] In general, this flowchart shows the flow and processing of data when a user requests a page in server-side rendering mode. The user first requests a page from the browser, the browser then requests data from the server, the server renders the page and returns it to the browser, and finally the browser displays the page to the user. This mode can reduce the rendering burden of the client (browser), improve the page loading speed and user experience.
[0040] In this embodiment, step S2 in the server-side rendering process specifically includes: Step S21: Code imports React library: The code first imports React library to provide basic support for the construction of server-side rendering related components; Step S22: Define a React component: define a stateless function component named HomePage for receiving data attributes, which receives an attribute named data; the component returns an HTML structure containing a title and a paragraph; the paragraph displays the input data; Step S23: Get server-side properties: an asynchronous function named getServerSideProps, which is used to obtain data on the server side; This asynchronous function uses the fetch function to get data from the API interface. The fetch function returns a promise, which is resolved into a response object. The response object is parsed into data in JSON format. The function returns an object that contains a property called props, which is itself an object containing the data obtained from the API.
[0041] Step S24: Data transfer and page rendering: The getServerSideProps asynchronous function is executed on the server side to obtain data from the API and pass the data as attributes to the HomePage component. When a page request occurs, the server renders the HomePage component with preloaded data and sends HTML to the client. After the client receives the prerendered page, it displays the page content containing the API data.
[0042] like Figure 4 As shown, step S3 in this embodiment specifically includes: Step S31: Configure module export: Use the module export method of Node.js, that is, use the module.exports object to define the configuration object of Webpack, which serves as the configuration entry for Webpack to optimize static resources; Step S32: Optimization configuration: In the module.exports object, there is an optimization attribute, which is an object itself and is used to configure the optimization function of Webpack; Step S33: Code splitting settings: In the optimization object, there is a splitChunks property, which is also an object; the chunks property in the splitChunks object is set to all, indicating that Webpack will perform split optimization on all types of chunks; Step S34: Code compression: In the optimization object, the minimize attribute is set to true; Webpack's ability to compress all output code packages is enabled, including compressing the output code packages through UglifyJS or Terser plug-ins. Compression can reduce the size of the output file and improve loading speed and performance; Step S35: Performance optimization and user experience improvement: With this configuration, Webpack can manage project resources more efficiently and reduce the amount of data required for the first load through code splitting and compression; Users will experience faster page loading speeds, and developers can reduce network transmission through cache optimization, which is especially important for large applications. This configuration method is suitable for large-scale web applications that need to optimize resource loading and performance, and can significantly improve the application's response speed and user satisfaction.
[0043] like Figure 5 The figure shows a schematic diagram of data prefetching in this implementation. The process starts with the user (User), who sends a "page request" operation to the browser through an operation (such as entering a URL in the browser or clicking a link). After the browser receives the user's request, it sends a prefetch data operation to the API while the page is loading. This step is the core operation of data prefetching, that is, the browser obtains the data that may be needed for the page from the API in advance. After receiving the browser's prefetch data request, the API returns the data to the browser.
[0044] After receiving the pre-fetched data, the browser performs the operation of displaying the page and presents the page to the user. At this time, since the data has been pre-fetched, the page can be loaded and displayed faster. Figure 5 This shows the flow and processing of data when a user requests a page in data prefetching mode. The user first requests a page from the browser, and the browser prefetches data while loading the page. After the API returns the data, the browser displays the page to the user. This mode can reduce the time users wait for data to load, improve page loading speed and user experience.
[0045] In this embodiment, step S4 specifically includes: Step S41: Use the useEffect hook: Use the useEffect hook function in the React component to handle the side effect operation of obtaining data from the remote API. The useEffect function accepts two parameters, one is the function that performs the data acquisition operation, and the other is the dependency array. By setting the dependency array to an empty array, ensure that the data acquisition operation is only performed once when the component is first rendered; Step S42: Define an asynchronous data acquisition function: define an asynchronous function named fetchData to perform data acquisition operations. Inside the fetchData function, use the fetch function to call an API to obtain data; the fetch function returns a promise, which provides a response object after being resolved; Step S43: Process the response and update the state: Use the await keyword to wait for the response of the fetch function, and then use the res.json method to convert the response body into JSON format data; call the setData function to update the state of the component and save the acquired data to the state; this will trigger the re-rendering of the component to display the new data; Step S44: trigger the data acquisition function: call fetchData in the side effect function of useEffect to ensure that the data is acquired immediately after the component is rendered for the first time; Step S45: Optimize user experience and performance: By obtaining data only once when the component is loaded, unnecessary network requests and resource consumption are reduced; ensure timely data updates and correct state management, and improve application responsiveness and user satisfaction.
[0046] like Figure 6 FIG. 1 is a schematic diagram of the cache mechanism of this embodiment; the process starts when a user issues a "request for resources" through a browser.
[0047] After the browser receives the request, it calls the ServiceWorker script; ServiceWorker is a script that runs in the background of the browser and is responsible for processing network requests and cache operations. After receiving the request, ServiceWorker will first "check the cache" (CheckCache) to determine whether the resource requested by the user is in the cache. If the requested resource is in the cache, ServiceWorker will "return the cached resource" to the browser, and the browser will directly use the cached resource for display. This step can reduce repeated requests and increase the speed of resource loading. If the requested resource is not in the cache, ServiceWorker will "initiate a network request" to obtain the resource from the server. After receiving the request from ServiceWorker, the server will return the resource to the ServiceWorker script. After ServiceWorker receives the resource returned by the server, it will cache the new resource and store the newly obtained resource in the cache so that it can be directly obtained from the cache when the same resource is requested later. Finally, ServiceWorker returns the resource obtained from the cache or server to the browser, and the browser displays it. Figure 6It shows the flow and processing of data when a user requests a resource under the cache mechanism. After the user requests a resource, the browser calls ServiceWorker, which checks the cache and obtains the resource from the cache or server according to the cache status. It caches the new resource and returns it to the browser for display. This mechanism can effectively reduce repeated requests and increase the speed of resource loading.
[0048] In the implementation of the cache mechanism in this embodiment, step S5 specifically includes: Step S51: Register a fetch event listener in ServiceWorker: Use the event listening mechanism of ServiceWorker to register a fetch event listener through the self.addEventListener method. The listener is triggered when the browser initiates a resource acquisition request, including one or more resource requests such as loading web pages, pictures, and CSS files; Step S52: intercepting and processing the network request: in the callback function of the fetch event, use the event.respondWith method to intercept the original network request of the browser and provide a custom response processing logic; Step S53: Check whether the requested resource exists in the cache: check whether there is a cache item matching the requested resource in the cache under the current domain through the caches.match method, which returns a Promise object; Step S54: Return cached resources or make a network request: If a matching cache item is successfully found, the cached resource is directly returned as a response (data is returned from the cache) to avoid repeated network requests; if no matching resource is found in the cache, fetch(event.request) is executed to initiate an actual network request to obtain the resource (request data from the server); Step S55: Cache newly acquired resources: For new resources successfully acquired from the network / server, use the caches.open method to open the cache space with the specified name, and then use the cache.put method to add the newly acquired resources to the cache. When adding the cache, it is necessary to use the response.clone method to copy the response object, because the original response object can only be read once, and the put method and returning the response to the browser both require reading the response content; Step S56: Return a response to the browser: Finally, the resource obtained from the cache or the resource obtained from the network request and cached is returned to the browser through the event.respondWith method to complete the response to the request.
[0049] A second aspect of the present invention provides a page loading speed comprehensive optimization system based on a React framework, the system is used to implement the above method, and the system comprises: The code splitting module is configured to perform code splitting operations, specifically: Define a lazy loading component named LazyComponent through React.lazy function. This function accepts a function that calls the import function to dynamically import components as a parameter, so as to realize dynamic loading of components; Use the Suspense component to wrap the defined LazyComponent lazy loading component, and set a React element for its fallback attribute to display a waiting prompt to the user during the loading of the lazy loading component; Inside the Suspense component, render the LazyComponent as a child component. When the component is first rendered, React will try to load the LazyComponent lazy loading component. Before the component is loaded, the user will see the content defined in the fallback property. The server-side rendering module is configured to execute the server-side rendering process, specifically: The code introduces the React library to provide basic support for the construction of server-side rendering related components; A stateless function component named HomePage is defined to receive data attributes. It receives an attribute named data. The component returns an HTML structure containing a title and a paragraph. The paragraph displays the passed data. Define an asynchronous function named getServerSideProps to get data on the server side. The asynchronous function uses the fetch function to get data from the API interface. The fetch function returns a promise that resolves to a response object. The response object is parsed into JSON format. The function returns an object that contains a property named props, which is itself an object containing the data obtained from the API. The getServerSideProps asynchronous function is executed on the server side to obtain data from the API and pass the data as attributes to the HomePage component. When a page request occurs, the server renders the HomePage component with preloaded data and sends the HTML to the client. After the client receives the prerendered page, it displays the page content containing the API data. The static resource optimization module is configured to perform static resource optimization, specifically: Through the module export method of Node.js, that is, using the module.exports object to define the configuration object of Webpack, which serves as the configuration entry for Webpack to optimize static resources; In the module.exports object, there is an optimization property, which is itself an object used to configure the optimization function of Webpack; The optimization object contains a splitChunks property, which is also an object. The chunks property in the splitChunks object is set to all, indicating that Webpack will perform segmentation optimization on all types of chunks. In the optimization object, the minimize property is set to true; this enables Webpack's ability to compress all output code bundles, including compressing the output code bundles through UglifyJS or Terser plugins. Compression can reduce the size of the output file and improve loading speed and performance; Through configuration, Webpack can manage project resources more efficiently and reduce the amount of data required for initial loading through code segmentation and compression; The data pre-fetching module is configured to execute the data pre-fetching strategy, specifically: In the React component, useEffect hook function is used to handle the side effect operation of obtaining data from the remote API. The useEffect function accepts two parameters, one is the function that performs the data acquisition operation, and the other is the dependency array. By setting the dependency array to an empty array, ensure that the data acquisition operation is only performed once when the component is first rendered; Define an asynchronous function named fetchData to perform data retrieval operations. Inside the fetchData function, use the fetch function to call an API to retrieve data; the fetch function returns a promise, which provides a response object after resolution; Use the await keyword to wait for the response of the fetch function, and then use the res.json method to convert the response body into JSON format data; call the setData function to update the state of the component and save the acquired data to the state; this will trigger the re-rendering of the component and display the new data; Call fetchData in the side effect function of useEffect to ensure that the data is obtained immediately after the component is rendered for the first time; By obtaining data only once when the component is loaded, unnecessary network requests and resource consumption are reduced; timely data updates and correct state management are ensured, improving application responsiveness and user satisfaction; The cache mechanism module is configured to perform cache mechanism implementation, specifically: Using the event listening mechanism of ServiceWorker, register a fetch event listener through the self.addEventListener method. This listener is triggered when the browser initiates a resource acquisition request, including one or more resource requests such as loading web pages, images, and CSS files; In the callback function of the fetch event, use the event.respondWith method to intercept the browser's original network request and provide a custom response processing logic; Use the caches.match method to check whether there is a cache item matching the resource in the cache under the current domain. This method returns a Promise object. If a matching cache item is successfully found, the cached resource is directly returned as a response to avoid repeated network requests; if no matching resource is found in the cache, fetch(event.request) is executed to initiate an actual network request to obtain the resource; For new resources successfully obtained from the network, use the caches.open method to open the cache space with the specified name, and then use the cache.put method to add the newly obtained resources to the cache. When adding the cache, you need to use the response.clone method to copy the response object, because the original response object can only be read once, and the put method and returning the response to the browser both require reading the response content; Finally, the event.respondWith method is used to return the resources obtained from the cache or the resources obtained from the network request and cached to the browser to complete the response to the request.
[0050] Although the embodiments of the present invention have been shown and described above, it will be appreciated that the above embodiments are exemplary and are not to be construed as limitations of the present invention. A person skilled in the art may change, modify, substitute and vary the above embodiments within the scope of the present invention.
Claims
1. A comprehensive optimization method for page loading speed based on the React framework, characterized in that: The following steps are involved: Step S1: Code splitting operation: By using the React.lazy function and Suspense component in the React framework to perform code splitting, components can be loaded on demand to reduce the initial loading time of the application; Step S2: Server-side rendering process, combined with the Next.js framework, implements server-side rendering, moves part of the rendering work to the server to reduce client-side rendering pressure; Step S3: Static resource optimization, by using the Webpack tool to compress and merge static resources, reducing the number of HTTP requests and resource size; Step S4: Data pre-fetching strategy, based on the lifecycle hook mechanism of the React component, pre-fetches the required data before the user accesses the page to reduce the user's waiting time; Step S5: Implement the cache mechanism, using the browser cache and server cache functions to reduce repeated resource acquisition requests.
2. The method for optimizing page loading speed based on the React framework according to claim 1, characterized in that: The step S1 specifically includes: Step S11: define a lazy loading component: use the React.lazy function of the React framework to define a lazy loading component named LazyComponent, which accepts a function that calls the import function to dynamically import components as a parameter, thereby realizing dynamic loading of components; Step S12: Wrap the lazy loading component with the Suspense component: Wrap the defined LazyComponent lazy loading component with the Suspense component, and set a React element for its fallback attribute to display a waiting prompt to the user during the loading of the lazy loading component; Step S13: Render the lazy component: Inside the Suspense component, render the LazyComponent as a child component. When the component is rendered for the first time, React will try to load the LazyComponent lazy component; before the component is loaded, the user will see the content defined in the fallback attribute.
3. The method for optimizing page loading speed based on the React framework according to claim 1, characterized in that: The step S2 specifically includes: Step S21: Code imports React library: The code first imports React library to provide basic support for the construction of server-side rendering related components; Step S22: Define a React component: define a stateless function component named HomePage for receiving data attributes, which receives an attribute named data; the component returns an HTML structure containing a title and a paragraph; the paragraph displays the input data; Step S23: Get server-side properties: an asynchronous function named getServerSideProps, which is used to obtain data on the server side; This asynchronous function uses the fetch function to get data from the API interface. The fetch function returns a promise, which is resolved to a response object. The response object is parsed into data in JSON format. The function returns an object that contains a property called props, which is itself an object containing the data obtained from the API. Step S24: Data transfer and page rendering: The getServerSideProps asynchronous function is executed on the server side to obtain data from the API and pass the data as attributes to the HomePage component. When a page request occurs, the server renders the HomePage component with preloaded data and sends HTML to the client. After the client receives the prerendered page, it displays the page content containing the API data.
4. The method for optimizing page loading speed based on the React framework according to claim 1, characterized in that: The step S3 specifically includes: Step S31: Configure module export: Use the module export method of Node.js, that is, use the module.exports object to define the configuration object of Webpack, which serves as the configuration entry for Webpack to optimize static resources; Step S32: Optimization configuration: In the module.exports object, there is an optimization attribute, which is an object itself and is used to configure the optimization function of Webpack; Step S33: Code splitting settings: In the optimization object, there is a splitChunks property, which is also an object; the chunks property in the splitChunks object is set to all, indicating that Webpack will perform split optimization on all types of chunks; Step S34: Code compression: In the optimization object, the minimize attribute is set to true; Webpack's ability to compress all output code packages is enabled, including compressing the output code packages through UglifyJS or Terser plug-ins. Compression can reduce the size of the output file and improve loading speed and performance; Step S35: Performance optimization and user experience improvement: Through configuration, Webpack can manage project resources more efficiently and reduce the amount of data required for initial loading through code splitting and compression.
5. The method for optimizing page loading speed based on the React framework according to claim 1, characterized in that: The step S4 specifically includes: Step S41: Use the useEffect hook: Use the useEffect hook function in the React component to handle the side effect operation of obtaining data from the remote API. The useEffect function accepts two parameters, one is the function that performs the data acquisition operation, and the other is the dependency array. By setting the dependency array to an empty array, ensure that the data acquisition operation is only performed once when the component is first rendered; Step S42: define an asynchronous data acquisition function: define an asynchronous function named fetchData to perform data acquisition operations; inside the fetchData function, use the fetch function to call an API to obtain data; the fetch function returns a promise, which provides a response object after being resolved; Step S43: Process the response and update the state: Use the await keyword to wait for the response of the fetch function, and then use the res.json method to convert the response body into JSON format data; call the setData function to update the state of the component and save the acquired data to the state; this will trigger the re-rendering of the component to display the new data; Step S44: trigger the data acquisition function: call fetchData in the side effect function of useEffect to ensure that the data is acquired immediately after the component is rendered for the first time; Step S45: Optimize user experience and performance: By obtaining data only once when the component is loaded, unnecessary network requests and resource consumption are reduced; ensure timely data updates and correct state management, and improve application responsiveness and user satisfaction.
6. The method for optimizing page loading speed based on the React framework according to claim 1, characterized in that: The step S5 specifically includes: Step S51: Register a fetch event listener in ServiceWorker: Use the event listening mechanism of ServiceWorker to register a fetch event listener through the self.addEventListener method. The listener is triggered when the browser initiates a resource acquisition request, including one or more resource requests such as loading web pages, pictures, and CSS files; Step S52: intercepting and processing the network request: in the callback function of the fetch event, use the event.respondWith method to intercept the original network request of the browser and provide a custom response processing logic; Step S53: Check whether the requested resource exists in the cache: check whether there is a cache item matching the requested resource in the cache under the current domain through the caches.match method, which returns a Promise object; Step S54: Return cached resources or make a network request: If a matching cache item is successfully found, the cached resource is directly returned as a response to avoid repeated network requests; if no matching resource is found in the cache, fetch(event.request) is executed to initiate an actual network request to obtain the resource; Step S55: Cache newly acquired resources: For new resources successfully acquired from the network, use the caches.open method to open the cache space with the specified name, and then use the cache.put method to add the newly acquired resources to the cache. When adding the cache, you need to use the response.clone method to copy the response object, because the original response object can only be read once, and the put method and returning the response to the browser both require reading the response content; Step S56: Return a response to the browser: Finally, the resource obtained from the cache or the resource obtained from the network request and cached is returned to the browser through the event.respondWith method to complete the response to the request.
7. A comprehensive optimization system for page loading speed based on React framework, characterized in that: The system is used to implement the method described in any one of claims 1 to 6, and the system includes: A code segmentation module, which is configured to perform the code segmentation operation according to claim 2, specifically: Define a lazy loading component named LazyComponent through React.lazy function. This function accepts a function that calls the import function to dynamically import components as a parameter, so as to realize dynamic loading of components; Use the Suspense component to wrap the defined LazyComponent lazy loading component, and set a React element for its fallback attribute to display a waiting prompt to the user during the loading of the lazy loading component; Inside the Suspense component, render the LazyComponent as a child component. When the component is first rendered, React will try to load the LazyComponent lazy loading component. Before the component is loaded, the user will see the content defined in the fallback property. The server-side rendering module is configured to execute the server-side rendering process described in claim 3, specifically: The code introduces the React library to provide basic support for the construction of server-side rendering related components; A stateless function component named HomePage is defined to receive data attributes. It receives an attribute named data. The component returns an HTML structure containing a title and a paragraph. The paragraph displays the passed data. Define an asynchronous function named getServerSideProps to get data on the server side. The asynchronous function uses the fetch function to get data from the API interface. The fetch function returns a promise that resolves to a response object. The response object is parsed into JSON format. The function returns an object that contains a property named props, which is itself an object containing the data obtained from the API. The getServerSideProps asynchronous function is executed on the server side to obtain data from the API and pass the data as attributes to the HomePage component. When a page request occurs, the server renders the HomePage component with preloaded data and sends the HTML to the client. After the client receives the prerendered page, it displays the page content containing the API data. The static resource optimization module is configured to perform the static resource optimization described in claim 4, specifically: Through the module export method of Node.js, that is, using the module.exports object to define the configuration object of Webpack, which serves as the configuration entry for Webpack to optimize static resources; In the module.exports object, there is an optimization property, which is itself an object used to configure the optimization function of Webpack; The optimization object contains a splitChunks property, which is also an object. The chunks property in the splitChunks object is set to all, indicating that Webpack will perform segmentation optimization on all types of chunks. In the optimization object, the minimize property is set to true; this enables Webpack's ability to compress all output code bundles, including compressing the output code bundles through UglifyJS or Terser plugins. Compression can reduce the size of the output file and improve loading speed and performance; Through configuration, Webpack can manage project resources more efficiently and reduce the amount of data required for initial loading through code segmentation and compression; A data pre-fetching module, which is configured to execute the data pre-fetching strategy according to claim 5, specifically: In the React component, useEffect hook function is used to handle the side effect operation of obtaining data from the remote API. The useEffect function accepts two parameters, one is the function that performs the data acquisition operation, and the other is the dependency array. By setting the dependency array to an empty array, ensure that the data acquisition operation is only performed once when the component is first rendered; Define an asynchronous function named fetchData to perform data retrieval operations; inside the fetchData function, use the fetch function to call an API to get data; the fetch function returns a promise, which provides a response object after resolution; Use the await keyword to wait for the response of the fetch function, and then use the res.json method to convert the response body into JSON format data; call the setData function to update the state of the component and save the acquired data to the state; this will trigger the re-rendering of the component and display the new data; Call fetchData in the side effect function of useEffect to ensure that the data is obtained immediately after the component is rendered for the first time; By obtaining data only once when the component is loaded, unnecessary network requests and resource consumption are reduced; timely data updates and correct state management are ensured, improving application responsiveness and user satisfaction; The cache mechanism module is configured to execute the cache mechanism implementation of claim 6, specifically: Using the event listening mechanism of ServiceWorker, register a fetch event listener through the self.addEventListener method. This listener is triggered when the browser initiates a resource acquisition request, including one or more resource requests such as loading web pages, images, and CSS files; In the callback function of the fetch event, use the event.respondWith method to intercept the browser's original network request and provide a custom response processing logic; Use the caches.match method to check whether there is a cache item matching the resource in the cache under the current domain. This method returns a Promise object. If a matching cache item is successfully found, the cached resource is directly returned as a response to avoid repeated network requests; if no matching resource is found in the cache, fetch(event.request) is executed to initiate an actual network request to obtain the resource; For new resources successfully obtained from the network, use the caches.open method to open the cache space with the specified name, and then use the cache.put method to add the newly obtained resources to the cache. When adding the cache, you need to use the response.clone method to copy the response object, because the original response object can only be read once, and the put method and returning the response to the browser both require reading the response content; Finally, the event.respondWith method is used to return the resources obtained from the cache or the resources obtained from the network request and cached to the browser to complete the response to the request.
Citation Information
Patent Citations
Processing method and device for increasing Vue frame page loading speed
CN119089064A
Cited By
Front-end development optimization method and system
CN121579014A