Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Lazy load stimulus controllers on the storefront (#12564)

Damian Kaczmarczyk5f9a2b09de25
diff --git a/core/config/importmap.rb b/core/config/importmap.rb
index 2156dafef9..6fe5693891 100644
--- a/core/config/importmap.rb
+++ b/core/config/importmap.rb
@@ -1,13 +1,13 @@
# Shared dependencies between storefront and admin
pin '@rails/request.js', to: '@rails--request.js.js', preload: ['application-spree-admin'] # @0.0.8
pin 'tailwindcss-stimulus-components', preload: ['application-spree-storefront', 'application-spree-admin'] # @3.0.4
-pin 'stimulus-reveal-controller', preload: ['application-spree-storefront', 'application-spree-admin'] # @4.1.0
+pin 'stimulus-reveal-controller', preload: ['application-spree-admin'] # @4.1.0
pin '@stimulus-components/auto-submit', to: '@stimulus-components--auto-submit.js', preload: ['application-spree-admin'] # @6.0.0
pin_all_from Spree::Core::Engine.root.join('app/javascript/spree/core/controllers'),
under: 'spree/core/controllers',
to: 'spree/core/controllers',
- preload: ['application-spree-storefront', 'application-spree-admin']
+ preload: ['application-spree-admin']
pin_all_from Spree::Core::Engine.root.join('app/javascript/spree/core/helpers'),
under: 'spree/core/helpers',
to: 'spree/core/helpers',
diff --git a/storefront/app/javascript/spree/storefront/application.js b/storefront/app/javascript/spree/storefront/application.js
index 58403af10a..4d75b0e5cd 100644
--- a/storefront/app/javascript/spree/storefront/application.js
+++ b/storefront/app/javascript/spree/storefront/application.js
@@ -11,88 +11,73 @@ if (typeof window.Stimulus === "undefined") {
application = window.Stimulus
}
-import AccordionController from 'spree/storefront/controllers/accordion_controller'
-import AccountNavController from 'spree/storefront/controllers/account_nav_controller'
-import AddressAutocompleteController from 'spree/core/controllers/address_autocomplete_controller'
-import AddressFormController from 'spree/core/controllers/address_form_controller'
-import AutoSubmit from '@stimulus-components/auto-submit'
-import CardValidationController from 'spree/storefront/controllers/card_validation_controller'
-import CartController from 'spree/storefront/controllers/cart_controller'
-import CheckoutAddressBookController from 'spree/storefront/controllers/address_book_controller'
-import CheckoutDeliveryController from 'spree/storefront/controllers/delivery_controller'
-import CheckoutPromotionsController from 'spree/storefront/controllers/promotions_controller'
-import CheckoutSummaryController from 'spree/storefront/controllers/summary_controller'
-import ClearInputController from 'spree/storefront/controllers/clear_input_controller'
-import CopyInputController from 'spree/storefront/controllers/copy_input_controller'
-import DropdownController from 'spree/storefront/controllers/dropdown_controller'
-import EnableButtonController from 'spree/core/controllers/enable_button_controller'
-import HeaderController from 'spree/storefront/controllers/header_controller'
-import InfiniteScrollController from 'spree/storefront/controllers/infinite_scroll_controller'
-import LightboxController from 'spree/storefront/controllers/lightbox_controller'
-import MobileNavController from 'spree/storefront/controllers/mobile_nav_controller'
-import ModalController from 'spree/storefront/controllers/modal_controller'
-import NoUiSliderController from 'spree/storefront/controllers/no_ui_slider_controller'
-import PDPDesktopGallery from 'spree/storefront/controllers/pdp_desktop_gallery'
-import PlpVariantPickerController from 'spree/storefront/controllers/plp_variant_picker_controller'
-import ProductFormController from 'spree/storefront/controllers/product_form_controller'
-import QuantityPickerController from 'spree/storefront/controllers/quantity_picker_controller'
-import SearchableListController from 'spree/storefront/controllers/searchable_list_controller'
-import SearchSuggestionsController from 'spree/storefront/controllers/search_suggestions_controller'
-import SlideoverController from 'spree/storefront/controllers/slideover_controller'
-import StickyButtonController from 'spree/storefront/controllers/sticky_button_controller'
-import SwiperController from 'spree/storefront/controllers/swiper_controller'
-import ToggleMenuController from 'spree/storefront/controllers/toggle_menu_controller'
-import TurboStreamFormController from 'spree/storefront/controllers/turbo_stream_form_controller'
-import WishedItemController from 'spree/storefront/controllers/wished_item_controller'
-
-application.register('accordion', AccordionController)
-application.register('account-nav', AccountNavController)
-application.register('address-autocomplete', AddressAutocompleteController)
-application.register('address-form', AddressFormController)
-application.register('auto-submit', AutoSubmit)
-application.register('card-validation', CardValidationController)
-application.register('cart', CartController)
-application.register('checkout-address-book', CheckoutAddressBookController)
-application.register('checkout-delivery', CheckoutDeliveryController)
-application.register('checkout-promotions', CheckoutPromotionsController)
-application.register('clear-input', ClearInputController)
-application.register('copy-input', CopyInputController)
-application.register('dropdown', DropdownController)
-application.register('enable-button', EnableButtonController)
-application.register('header', HeaderController)
-application.register('infinite-scroll', InfiniteScrollController)
-application.register('lightbox', LightboxController)
-application.register('mobile-nav', MobileNavController)
-application.register('modal', ModalController)
-application.register('no-ui-slider', NoUiSliderController)
-application.register('pdp-desktop-gallery', PDPDesktopGallery)
-application.register('plp-variant-picker', PlpVariantPickerController)
-application.register('product-form', ProductFormController)
-application.register('quantity-picker', QuantityPickerController)
-application.register('search-suggestions', SearchSuggestionsController)
-application.register('searchable-list', SearchableListController)
-application.register('slideover', SlideoverController)
-application.register('slideover-account', SlideoverController)
-application.register('sticky-button', StickyButtonController)
-application.register('checkout-summary', CheckoutSummaryController)
-application.register('carousel', SwiperController)
-application.register('toggle-menu', ToggleMenuController)
-application.register('turbo-stream-form', TurboStreamFormController)
-application.register('wished-item', WishedItemController)
-
-// Import and register all TailwindCSS Components
import { Alert, Toggle } from 'tailwindcss-stimulus-components'
application.register('alert', Alert)
application.register('toggle', Toggle)
-import Reveal from 'stimulus-reveal-controller'
-application.register('reveal', Reveal)
-import ScrollTo from 'stimulus-scroll-to'
-application.register('scroll-to', ScrollTo)
+// We need to preload the carousel controller, otherwise it causes a huge layout shift when it's loaded.
+import CarouselController from 'spree/storefront/controllers/carousel_controller'
+application.register('carousel', CarouselController)
+
+// We need to make allow list of controllers to be loaded, this is needed because by default Stimulus will try to load all the controllers that it encounters in the DOM.
+// Since Spree Storefront can be extended with custom views/partials, we need to be able to control which controllers can be loaded from our application.
+
+const controllers = [
+ 'accordion',
+ 'account-nav',
+ 'address-autocomplete',
+ 'address-form',
+ 'auto-submit',
+ 'card-validation',
+ 'cart',
+ 'checkout-address-book',
+ 'checkout-delivery',
+ 'checkout-promotions',
+ 'checkout-summary',
+ 'clear-input',
+ 'copy-input',
+ 'dropdown',
+ 'enable-button',
+ 'header',
+ 'infinite-scroll',
+ 'lightbox',
+ 'mobile-nav',
+ 'modal',
+ 'no-ui-slider',
+ 'pdp-desktop-gallery',
+ 'plp-variant-picker',
+ 'product-form',
+ 'quantity-picker',
+ 'read-more',
+ 'reveal',
+ 'scroll-to',
+ 'search-suggestions',
+ 'searchable-list',
+ 'slideover-account',
+ 'slideover',
+ 'sticky-button',
+ 'toggle-menu',
+ 'turbo-stream-form',
+ 'wished-item',
+]
+
+
+// Manifest is needed to load controllers that names don't match the controller filename, or are not in the controllers directory.
+const manifest = {
+ "auto-submit": "@stimulus-components/auto-submit",
+ "address-form": "spree/core/controllers/address_form_controller",
+ "address-autocomplete": "spree/core/controllers/address_autocomplete_controller",
+ "enable-button": "spree/core/controllers/enable_button_controller",
+ "slideover-account": "spree/storefront/controllers/slideover_controller",
+ "reveal": "stimulus-reveal-controller",
+ "scroll-to": "stimulus-scroll-to",
+ "read-more": "stimulus-read-more",
+}
+
+import { lazyLoadControllersFromManifest } from "spree/storefront/helpers/lazy_load_controllers_with_manifest"
-import ReadMore from 'stimulus-read-more'
-application.register('read-more', ReadMore)
+lazyLoadControllersFromManifest(controllers, "spree/storefront/controllers", application, manifest)
const scrollToOverlay = (overlay) => {
diff --git a/storefront/app/javascript/spree/storefront/controllers/swiper_controller.js b/storefront/app/javascript/spree/storefront/controllers/carousel_controller.js
similarity index 100%
rename from storefront/app/javascript/spree/storefront/controllers/swiper_controller.js
rename to storefront/app/javascript/spree/storefront/controllers/carousel_controller.js
diff --git a/storefront/app/javascript/spree/storefront/controllers/address_book_controller.js b/storefront/app/javascript/spree/storefront/controllers/checkout_address_book_controller.js
similarity index 100%
rename from storefront/app/javascript/spree/storefront/controllers/address_book_controller.js
rename to storefront/app/javascript/spree/storefront/controllers/checkout_address_book_controller.js
diff --git a/storefront/app/javascript/spree/storefront/controllers/promotions_controller.js b/storefront/app/javascript/spree/storefront/controllers/checkout_promotions_controller.js
similarity index 100%
rename from storefront/app/javascript/spree/storefront/controllers/promotions_controller.js
rename to storefront/app/javascript/spree/storefront/controllers/checkout_promotions_controller.js
diff --git a/storefront/app/javascript/spree/storefront/controllers/summary_controller.js b/storefront/app/javascript/spree/storefront/controllers/checkout_summary_controller.js
similarity index 100%
rename from storefront/app/javascript/spree/storefront/controllers/summary_controller.js
rename to storefront/app/javascript/spree/storefront/controllers/checkout_summary_controller.js
diff --git a/storefront/app/javascript/spree/storefront/controllers/lightbox_controller.js b/storefront/app/javascript/spree/storefront/controllers/lightbox_controller.js
index ae269852da..42e5fb75a3 100644
--- a/storefront/app/javascript/spree/storefront/controllers/lightbox_controller.js
+++ b/storefront/app/javascript/spree/storefront/controllers/lightbox_controller.js
@@ -19,6 +19,8 @@ function isTouchDevice() {
}
export default class extends Controller {
connect() {
+ this.addPhotoSwipeStyles()
+
const lightbox = new PhotoSwipeLightbox({
gallery: this.element,
children: 'a',
@@ -120,4 +122,17 @@ export default class extends Controller {
return pinchToZoom
}
+
+ addPhotoSwipeStyles() {
+ if (document.getElementById('photoswipe-styles')) {
+ return
+ }
+
+ const link = document.createElement('link')
+ link.id = 'photoswipe-styles'
+ link.rel = 'stylesheet'
+ link.href = 'https://esm.sh/[email protected]/dist/photoswipe.css'
+ link.onerror = () => console.error('Failed to load PhotoSwipe CSS')
+ document.head.appendChild(link)
+ }
}
diff --git a/storefront/app/javascript/spree/storefront/controllers/pdp_desktop_gallery.js b/storefront/app/javascript/spree/storefront/controllers/pdp_desktop_gallery_controller.js
similarity index 100%
rename from storefront/app/javascript/spree/storefront/controllers/pdp_desktop_gallery.js
rename to storefront/app/javascript/spree/storefront/controllers/pdp_desktop_gallery_controller.js
diff --git a/storefront/app/javascript/spree/storefront/helpers/lazy_load_controllers_with_manifest.js b/storefront/app/javascript/spree/storefront/helpers/lazy_load_controllers_with_manifest.js
new file mode 100644
index 0000000000..0a2a1338ac
--- /dev/null
+++ b/storefront/app/javascript/spree/storefront/helpers/lazy_load_controllers_with_manifest.js
@@ -0,0 +1,78 @@
+const controllerAttribute = "data-controller"
+
+// This function is based on `lazyLoadControllersFrom` function from Stimulus.
+// https://github.com/hotwired/stimulus-rails/blob/main/app/assets/javascripts/stimulus-loading.js
+// We need to slightly modify it to fit our needs, mostly to make allow list of controllers to be loaded and to use manifest when controller is not in the controllers directory.
+// More information about what is `manifest` and what are `controllers` can be found in the `application.js` file.
+
+export function lazyLoadControllersFromManifest(controllers, under, application, manifest = {}, element = document) {
+ lazyLoadExistingControllers(controllers, under, application, manifest, element)
+ lazyLoadNewControllers(controllers, under, application, manifest, element)
+}
+
+function lazyLoadExistingControllers(controllers, under, application, manifest, element) {
+ queryControllerNamesWithin(element).forEach(controllerName => {
+ if (controllers.includes(controllerName)) {
+ loadController(controllerName, under, application, manifest)
+ }
+ }
+ )
+}
+
+function lazyLoadNewControllers(controllers, under, application, manifest, element) {
+ new MutationObserver((mutationsList) => {
+ for (const { attributeName, target, type } of mutationsList) {
+ switch (type) {
+ case "attributes": {
+ if (attributeName == controllerAttribute && target.getAttribute(controllerAttribute)) {
+ extractControllerNamesFrom(target).forEach(controllerName => {
+ if (controllers.includes(controllerName)) {
+ loadController(controllerName, under, application, manifest)
+ }
+ }
+ )
+ }
+ break;
+ }
+
+ case "childList": {
+ lazyLoadExistingControllers(controllers, under, application, manifest, target)
+ break;
+ }
+ }
+ }
+ }).observe(element, { attributeFilter: [controllerAttribute], subtree: true, childList: true })
+}
+
+function queryControllerNamesWithin(element) {
+ return Array.from(element.querySelectorAll(`[${controllerAttribute}]`)).map(extractControllerNamesFrom).flat()
+}
+
+function extractControllerNamesFrom(element) {
+ return element.getAttribute(controllerAttribute).split(/\s+/).filter(content => content.length)
+}
+
+function loadController(name, under, application, manifest) {
+ if (canRegisterController(name, application)) {
+ import(controllerFilename(name, under, manifest))
+ .then(module => registerController(name, module, application))
+ .catch(error => console.error(`Failed to autoload controller: ${name}`, error))
+ }
+}
+
+function controllerFilename(name, under, manifest) {
+ if (manifest && manifest[name]) {
+ return manifest[name]
+ }
+ return `${under}/${name.replace(/--/g, "/").replace(/-/g, "_")}_controller`
+}
+
+function registerController(name, module, application) {
+ if (canRegisterController(name, application)) {
+ application.register(name, module.default)
+ }
+}
+
+function canRegisterController(name, application) {
+ return !application.router.modulesByIdentifier.has(name)
+}
\ No newline at end of file
diff --git a/storefront/config/importmap.rb b/storefront/config/importmap.rb
index 402012f160..b8d6a87135 100644
--- a/storefront/config/importmap.rb
+++ b/storefront/config/importmap.rb
@@ -1,21 +1,21 @@
pin 'application-spree-storefront', to: 'spree/storefront/application.js', preload: false
-pin 'stimulus-scroll-to', preload: ['application-spree-storefront'] # @4.1.0
-pin 'stimulus-read-more', preload: ['application-spree-storefront'] # @4.1.0
-pin '@kanety/stimulus-accordion', to: '@kanety--stimulus-accordion.js', preload: ['application-spree-storefront'] # @1.1.0
-pin 'headroom.js', preload: ['application-spree-storefront'] # @0.12.0
-pin 'photoswipe/lightbox', to: 'photoswipe--dist--photoswipe-lightbox.esm.js.js', preload: ['application-spree-storefront'] # @5.4.4
-pin 'nouislider', preload: ['application-spree-storefront'] # @15.8.1
-pin 'swiper/bundle', to: 'https://ga.jspm.io/npm:[email protected]/swiper-bundle.mjs', preload: ['application-spree-storefront'] # @11.2.2
-pin '@stimulus-components/carousel', to: '@stimulus-components--carousel.js', preload: ['application-spree-storefront'] # @6.0.0
+pin 'stimulus-scroll-to', preload: false # @4.1.0
+pin 'stimulus-read-more', preload: false # @4.1.0
+pin '@kanety/stimulus-accordion', to: '@kanety--stimulus-accordion.js', preload: false # @1.1.0
+pin 'headroom.js', preload: false # @0.12.0
+pin 'photoswipe/lightbox', to: 'photoswipe--dist--photoswipe-lightbox.esm.js.js', preload: false # @5.4.4
+pin 'nouislider', preload: false # @15.8.1
+pin 'swiper/bundle', to: 'https://ga.jspm.io/npm:[email protected]/swiper-bundle.mjs', preload: false # @11.2.2
+pin '@stimulus-components/carousel', to: '@stimulus-components--carousel.js', preload: false # @6.0.0
pin 'photoswipe', preload: false # @5.4.4
-pin "card-validator", to: "card-validator.js", preload: ['application-spree-storefront'] # @10.0.2
-pin "credit-card-type", to: "credit-card-type.js", preload: ['application-spree-storefront'] # @10.0.2
+pin 'card-validator', to: 'card-validator.js', preload: false # @10.0.2
+pin 'credit-card-type', to: 'credit-card-type.js', preload: false # @10.0.2
pin_all_from Spree::Storefront::Engine.root.join('app/javascript/spree/storefront/controllers'),
under: 'spree/storefront/controllers',
to: 'spree/storefront/controllers',
- preload: ['application-spree-storefront']
+ preload: false
pin_all_from Spree::Storefront::Engine.root.join('app/javascript/spree/storefront/helpers'),
under: 'spree/storefront/helpers',
to: 'spree/storefront/helpers',
diff --git a/storefront/lib/generators/spree/storefront/install/templates/application.tailwind.css b/storefront/lib/generators/spree/storefront/install/templates/application.tailwind.css
index cf19b4ccf4..7a4c272b6e 100644
--- a/storefront/lib/generators/spree/storefront/install/templates/application.tailwind.css
+++ b/storefront/lib/generators/spree/storefront/install/templates/application.tailwind.css
@@ -1,4 +1,3 @@
-@import url("https://esm.sh/[email protected]/dist/photoswipe.css");
@import url("https://esm.sh/[email protected]/swiper-bundle.min.css");
@import url("https://esm.sh/[email protected]/css/flag-icons.min.css");