反应延迟加载-何时使用 [英] React lazy loading - when to use

查看:56
本文介绍了反应延迟加载-何时使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的应用程序,到目前为止,它的捆绑包大小约为2mb(3个块左右).为了缩短加载时间,我决定开始使用相对较新的 React Lazy .

I have a pretty large app, which by now has a bundle size of around 2mb combined (3 chunks or so). In order to improve loading times, I decided to start using the relatively new React Lazy.

这是一个懒惰导入的示例:

Here's an example of a lazy import:

const向导= React.lazy(()=> import('./components/wizards/Wizard'));

我了解总体思路,但除了要不时地加载一些块之外,我仍然很难理解其弊端.

I understand the general idea, but I still struggle to understand what's the downside, other than having to wait a bit to load a chunk from time to time.

根据我阅读的内容,我没有理由使用常规导入.

According to what I read, I have no reason to use a regular import.

我的问题是:我应该对应用程序中的每个组件导入都使用惰性导入吗?为什么?为什么不呢?

我很想听听你们的想法.

I'd love to hear what you guys think.

推荐答案

否,不需要每个组件.用于每个布局或页面是有意义的.路线是一个不错的起点.网络上的大多数人习惯了页面过渡,这需要花费一些时间来加载.您还倾向于一次重新渲染整个页面,因此您的用户不太可能同时与页面上的其他元素进行交互.

No, for every component it no needed. It make sense to use for each layout or page. A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.

例如,您为新闻聚合器创建应用程序.您的应用程序包括两个页面,例如 NewsList NewsItemPage .每个页面都包含几个不同的组件.在此示例中,对每个页面使用延迟加载组件是有意义的.然后它将加载所需的组件.

For example, you creating application for news aggregator. Your application include two pages such as NewsList and NewsItemPage. Every pages includes several different components. In this example make sense to use lazy loading component for each other page. And then it will load the components it needs.

该应用程序还具有 Header Footer .它们应该以通常的方式加载.由于它们用在每个页面上,因此异步加载毫无意义.

The application also has a Header and Footer. They should be loaded in the usual way. Since they are used on every page, and there is no point in asynchronous loading.

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>
);

这篇关于反应延迟加载-何时使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆