Principle:Langgenius Dify Dynamic Import Pattern
| Knowledge Sources | Dify |
|---|---|
| Domains | Frontend, Performance |
| Last Updated | 2026-02-12 07:00 GMT |
Overview
Lazy loading components via Next.js dynamic imports with SSR disabled for client-only components, reducing initial bundle size and improving page load performance.
Description
The Dynamic Import Pattern principle defines how Dify defers the loading of components that are not needed for the initial render. Using Next.js dynamic() function, components are loaded asynchronously when they are first needed rather than being included in the main JavaScript bundle. For components that rely on browser-only APIs (such as modals, rich text editors, or visualization libraries), SSR is explicitly disabled to prevent hydration mismatches.
In the Dify codebase, dynamic imports are used strategically for heavy or conditionally-rendered components. The Modal Context, for instance, uses dynamic imports for dialog components that are only rendered when triggered by user interaction. This means that the JavaScript code for modals, their dependencies, and any third-party libraries they use are not downloaded until the user actually opens a modal. The SSR disable flag (ssr: false) is applied to components that access window, document, or other browser globals that do not exist during server-side rendering.
This principle matters because Dify's frontend includes a large number of feature-rich components including workflow editors, code editors, chart visualizations, and complex form builders. Loading all of these components upfront would result in a large initial bundle that slows down the first meaningful paint. Dynamic imports enable code splitting at the component level, ensuring that users only download the JavaScript they need for their current view. This directly improves Core Web Vitals metrics like Largest Contentful Paint and Time to Interactive, which affect both user experience and search engine ranking.
Usage
Use this principle when:
- Adding new components that are heavy in file size or have large dependency trees
- Implementing components that are conditionally rendered based on user interaction
- Working with libraries that access browser-only APIs and cannot be server-side rendered
Theoretical Basis
Dynamic imports implement code splitting, a performance optimization technique where the application bundle is divided into smaller chunks that are loaded on demand. This builds on the ECMAScript dynamic import proposal (import()) which returns a Promise for the module. Next.js wraps this with React.lazy() and Suspense boundaries to provide a declarative loading experience. The SSR disable option addresses the isomorphic rendering challenge where server and client environments have different available APIs.