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 從公開儲存庫中收錄這些內容。

檢舉或申請下架