Eager vs Lazy loading controllers with Import Maps
mainIn an import-mapped application, you can control how controllers are loaded in app/javascript/controllers/index.js:
- Eager Loading: Uses
eagerLoadControllersFrom. All controllers are loaded when the application starts. This is suitable for a modest number of controllers. - Lazy Loading: Uses
lazyLoadControllersFrom. Controllers are only loaded when theirdata-controlleridentifier is encountered in the DOM. This is recommended if your application has a large number of controllers.
// app/javascript/controllers/index.js
import { application } from "controllers/application"
// For Eager Loading:
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
// For Lazy Loading:
import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"
lazyLoadControllersFrom("controllers", application)