import-on-visibility

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Import On Visibility

视口可见时加载组件

Besides user interaction, we often have components that aren't visible on the initial page. A good example of this is lazy loading images that aren't directly visible in the viewport, but only get loaded once the user scrolls down.
As we're not requesting all images instantly, we can reduce the initial loading time. We can do the same with components! In order to know whether components are currently in our viewport, we can use the
IntersectionObserver
API
, or use libraries such as
react-lazyload
or
react-loadable-visibility
to quickly add import on visibility to our application.
除了用户交互触发加载外,我们经常会遇到一些初始页面中不可见的组件。一个典型例子就是懒加载那些初始不在视口内的图片,只有当用户向下滚动时才会加载。
通过不立即请求所有图片,我们可以缩短初始加载时间。这种方式同样适用于组件!为了判断组件当前是否处于视口内,我们可以使用
IntersectionObserver
API
,或者借助
react-lazyload
react-loadable-visibility
这类库,快速为应用添加“视口可见时加载”的功能。

When to Use

使用场景

  • Use this for components that aren't visible on the initial page (e.g., below-the-fold content)
  • This is helpful for lazy loading images, widgets, or heavy components as the user scrolls
  • 适用于初始页面不可见的组件(例如,首屏下方的内容)
  • 有助于在用户滚动时懒加载图片、小部件或重型组件

Instructions

实现步骤

  • Use the
    IntersectionObserver
    API to detect when components enter the viewport
  • Use libraries like
    react-lazyload
    or
    react-loadable-visibility
    for quick implementation
  • Provide a loading fallback component while the module is being loaded
  • 使用
    IntersectionObserver
    API检测组件何时进入视口
  • 使用
    react-lazyload
    react-loadable-visibility
    等库快速实现
  • 在模块加载过程中提供加载占位组件

Details

细节说明

Whenever a component is rendered to the screen,
react-loadable-visibility
detects that the element should be visible on the screen. Only then, it will start importing the module while the user sees a loading component being rendered.
This fallback component lets the user know that our application hasn't frozen: they simply need to wait a short while for the module to be loaded, parsed, compiled, and executed!
每当组件即将渲染到屏幕上时,
react-loadable-visibility
会检测到该元素即将进入可视范围。只有此时,它才会开始导入模块,同时向用户展示加载中的组件。
这个占位组件可以让用户知道应用并未卡顿:他们只需稍作等待,模块就会完成加载、解析、编译和执行!

Source

来源