Back to Bundle Size Optimization

Conditional Module Loading

bundleconditional-loadinglazy-loading
28.0k🕒 2026-06-10Source ↗

Install this skill

npx skills add vercel-labs/agent-skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

Conditional Module Loading reduces initial JavaScript bundle sizes by deferring the importation of heavy dependencies until a specific interaction or state change requires them. This pattern targets non-critical code paths, ensuring browsers only download and execute modules when users trigger relevant features. By incorporating environmental checks, such as verifying the window object, the implementation safely isolates client-side dependencies from server-side rendering pipelines. This approach directly improves time-to-interactive metrics and decreases total payload weight. It transforms static imports into dynamic runtime events, preventing unnecessary execution of code segments that may never be accessed during a specific user session. The skill focuses on balancing feature richness with performance constraints, ensuring that high-memory assets like complex animation libraries or data-heavy visualizations do not penalize the initial page load time.

When to Use This Skill

  • Deferred loading of heavy data-visualization libraries
  • Initialization of secondary animation frame sets upon user interaction
  • Selective inclusion of client-side logic in SSR frameworks
  • On-demand attachment of markdown previewers or syntax highlighters

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • Reduce the initial bundle size for this feature
  • Lazy load this module only when activated
  • Prevent server-side rendering for this library
  • Delay loading of this script to improve performance
  • Import this package dynamically to optimize startup

What this skill does

  • Dynamic imports via ES syntax
  • Environment-aware module exclusion
  • Automatic skeleton screen synchronization
  • Error handling for failed network module fetches
  • Conditional execution based on component state

When not to use it

  • Critical UI elements required for the initial paint
  • Small modules that result in high overhead for promise resolution

Example workflow

  1. Identify a heavy library not needed during initial render
  2. Replace static import statement with dynamic import syntax
  3. Wrap the loading logic in a state-managed useEffect hook
  4. Implement a fallback UI or skeleton state for the loading duration
  5. Add environmental guards to prevent SSR execution
  6. Verify the module chunk splits correctly in build output

Prerequisites

  • Knowledge of dynamic import syntax
  • Basic understanding of component lifecycle hooks
  • Familiarity with module bundler configuration

Pitfalls & limitations

  • !Increased latency during the first interaction with the feature
  • !Complex error states if the external module fails to load over the network
  • !Potential layout shift when the deferred component finally renders

FAQ

Does this approach break server-side rendering?
No, the inclusion of conditional checks like typeof window prevents the code from executing in a Node.js environment, keeping the server bundle clean.
Will this cause layout shift?
It can if the container size changes abruptly. Using placeholders or skeleton screens during the loading state helps mitigate visual shifts.
When is the best time to trigger the load?
Usually inside an event handler or a useEffect hook that monitors a specific 'enabled' boolean state.

How it compares

Unlike manual script injection or generic code-splitting, this method provides a standardized, reactive lifecycle-integrated pattern that handles state transitions and conditional environmental execution automatically.

Source & trust

28k stars🕒 Updated 2026-06-10
📄 Full skill instructions — original source: vercel-labs/agent-skills
## Conditional Module Loading

Load large data or modules only when a feature is activated.

**Example (lazy-load animation frames):**

function AnimationPlayer({ enabled }: { enabled: boolean }) {
const [frames, setFrames] = useState<Frame[] | null>(null)

useEffect(() => {
if (enabled && !frames && typeof window !== 'undefined') {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames])

if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}


The typeof window !== 'undefined' check prevents bundling this module for SSR, optimizing server bundle size and build speed.

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/bundle-conditional/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/vercel-labs/agent-skills/bundle-conditional/SKILL.md
  • Cursor: ~/.cursor/skills/vercel-labs/agent-skills/bundle-conditional/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/vercel-labs/agent-skills/bundle-conditional/SKILL.md

🚀 Install with CLI:
npx skills add vercel-labs/agent-skills

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid bundle size optimization issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Bundle Size Optimization and is published by Vercel Engineering, maintained in vercel-labs/agent-skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.