Import On Visibility

patternsdev/skills/javascript/import-on-visibility

作者 patternsdev48bf58a488cdMIT253 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5个月前更新

Teaches visibility-based lazy loading using Intersection Observer. Use when you have below-the-fold components or images that don't need to load until the user scrolls to them.

AI 生成的概览

讲解如何使用 Intersection Observer 对首屏之外的组件和图片进行基于可见性的懒加载。

功能
该技能介绍 import-on-visibility 模式,用于将组件和图片的加载推迟到它们进入视口时。内容涵盖使用 IntersectionObserver API 或 react-lazyload、react-loadable-visibility 等库,并在模块加载期间提供加载占位组件。它还列出了不适用该模式的场景,例如首屏内容或对 SEO 关键的标记。
适用场景
当页面包含首屏之外的组件、图片、小组件或较重的模块,且这些内容在用户滚动到之前无需加载时使用。也适用于以缩短初始加载时间为目标、并且可以显示加载占位组件的场景。
运行要求
不附带脚本或软件包,仅为说明性内容。应用该模式需要 JavaScript 或 TypeScript 项目,以及浏览器的 IntersectionObserver API 或 react-lazyload、react-loadable-visibility 等库。

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.

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

When NOT to Use

  • For above-the-fold content that must render immediately — deferring it causes visible layout shifts and slow LCP
  • When the component is lightweight enough that lazy loading adds more overhead than it saves
  • When the content is critical for SEO and needs to be present in the initial HTML

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

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!

Source

来源与署名

来源:patternsdev/skills位于javascript/import-on-visibility提交48bf58a

许可证: MIT

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架