P粉7908197272023-08-25 19:12:59
I haven't started using it yet. But I think the most optimistic approach is to do regular imports of all the components you need on the homepage. Any other routes that are not the homepage should use lazy loading. This is the general train of thought I have.
P粉4810352322023-08-25 14:42:07
No, not required for every component. It only makes sense to use it in every layout or page. A good place to start is routing. Most people on the web are used to page transitions taking a certain amount of time to load. You also tend to re-render the entire page at once, so your users are less likely to interact with other elements on the page at the same time.
For example, you are creating a news aggregation application. Your application consists of two pages such as NewsList
and NewsItemPage
. Each page contains several different components. In this example, it makes sense to use lazy loading components for every other page. It will then load the components it needs.
The application also has a Header
and Footer
. They should be loaded in the usual way. Because they are used on every page and loading asynchronously doesn't make sense.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import React, { Suspense, lazy } from 'react'; import Header from './components/Header'; import Footer from './components/Footer'; const NewsList = lazy(() => import('./pages/NewsList')); const NewsItemPage = lazy(() => import('./pages/NewsItemPage')); const App = () => ( <Router> <Header /> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route exact path="/" component={NewsList}/> <Route path="/news/:id" component={NewsItemPage}/> </Switch> </Suspense> <Footer /> </Router> );