SoFunction
Updated on 2025-04-04

Implementation method for on-demand loading of spa based on vue and react

On-demand loading based on vue and react

Since I recently planned to use the same login method for all management systems, and then switch the system after logging in, and no need for each system to log in again, the front-end thought about building all systems with a spa application. However, after the merger of each system, the packaged code should be quite large. A single page needs to load all system resources at one time, which seems unrealistic, so I planned to separate the resources of different systems, and then select and load the corresponding resources of the system. I found that this service is similar to the routing of each system, so the system configuration is based on vue-router or react-router for on-demand loading. Therefore, I learned about the application and configuration scheme for loading on demand.

Based on this business, you have other solutions and welcome to communicate (_O_)

Load on demand

With the development of single-page applications, all functions of the entire system are collected in one page. The page loads all resources at once. As the system continues to expand, the loaded resources will continue to increase. Although the amount of the resource content is greatly reduced after compression processing, the increase in resource content cannot be essentially reduced.

In fact, our module corresponds to different resources, which is similar to the multi-page system we did before. Different pages load the corresponding resource files. Therefore, we can refer to the previous multi-page system practices to load the corresponding resource files according to different modules in a single-page system. It means that the user only loads the code corresponding to this function, which is the so-called on-demand loading.

How to load on demand

On-demand loading in a single page application, the following principles are generally adopted

  • Divide the entire system into small functions, and then divide it into several categories according to the degree of function correlation.
  • Merge each class into a Chunk and load the corresponding Chunk as needed
  • The content you see on the first screen is placed directly in the entrance Chunk to reduce the number of resources loaded on the web page for the first time
  • For other modules, you can do on-demand loading.

The loading of the divided code requires a certain mechanism to trigger, that is, it will be loaded when the user is about to operate the corresponding function. The loading timing of the divided code needs to be measured and determined by the needs of its own system.
Because the code that is split also takes a certain amount of time to load, preloading can be done in advance.

import()

Before starting the following case, let's first understand import(). The import() here is different from the import xxx from 'xxx' that introduces modules. The import here refers to a function that dynamically loads the module. The passed parameters are the corresponding module, but import() will return a Promise object, so it can be processed according to its status after import() is completed.

//eg
import('/component/details').then(mod=>{
  (mod)
},error=>{
  (error)
})

vue loading applications

1. Module segmentation

According to the situation of your own system, individuals divide it according to the vue-router module.

//Roter configuration split codeimport Vue from 'vue'
import Router from 'vue-router'
const listnav=()=> import('@/components/listnav')
const adminav=()=> import('@/components/adminav')
(Router)
const router = new Router({
  routes:[{
    path:'/listnav',
    name:'listnav',
    component:listnav
  },
  {
    path:'/adminav',
    name:'adminav',
    component:adminav
  }
  ]
})
export default router

Output file configuration

//
 = {
  entry:{
    app:'./src/'
  },
  output:{
    path:"../dist",
    filename:'js/[name].js',
    chunkFilename:'js/[name].js'
  }
}

react loads the app on demand

1. Module segmentation

The same module segmentation can be divided using react-router.

//Router configuration segmentation codeimport React, {PureComponent, Component ,createElement} from 'react';
import {HashRouter as Router, Route,Link,withRouter} from 'react-router-dom';
import Home from "../component/home"
function getAsyncComponent(load) {
 return class AsyncComponent extends PureComponent {
  constructor(props) {
   super(props);
  }
  componentDidMount() {
   // Only perform network loading steps when advanced component DidMount   load().then(({default: component}) => {
   // The code is loaded successfully, and the exported value of the code is obtained. Call setState to notify the higher-order component to re-render the subcomponent    ({
     component,
    })
   });
  }
  render() {
   const {component} =  || {};
   // component is type, and it is necessary to produce a component instance through   return component ? createElement(component) : null;
  }
 }
}
const Routes = () =>(
  <HashRouter>
    <Route path="/home/:test" exact component={Home}/>
    <Route path='/details/:id' component={getAsyncComponent(
     // Asynchronous loading function, asynchronously loading details components     () => import('../component/details')
    )}/>
  </HashRouter>
)
export default Routers;

Output file configuration

//
 = {
  entry:{
    main: "../src/", //Entry file  },
  output:{
    path:"../dist",//Export documents    filename:"js/[name].js",
    chunkFilename:"js/[name].js",
    publicPath: ''
  }
}

3. Load the props delivery in the component on demand

After loading on demand, the components loading on demand cannot receive the passed props, so they cannot obtain the parameters brought in when router configuration.

Workaround utilizing withRouter in react-router

Can be configured in components loaded on demand

//component/
import React, { Component } from 'react';
import {withRouter} from 'react-router-dom';
class Details extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    ()
    return (
      <div></div>
    )
  }
}
export default withRouter(Details);

Reference link

vue-router route lazy loading [/zh/guide/advanced/]

React loading on demand[/4%E4%BC%98%E5%8C%96/4-12%E6%8C%89%E9%9C%80%E5%8A%A0%E8%BD%]

Summarize

The above is the implementation method of on-demand loading of spas based on vue and react that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!