Skip to content

Commit 111fd4c

Browse files
committed
fix: lazy load Stimulus controllers with Turbo
1 parent 5487937 commit 111fd4c

File tree

2 files changed

+21
-29
lines changed

2 files changed

+21
-29
lines changed

src/StimulusBundle/assets/dist/loader.js

+8-13
Original file line numberDiff line numberDiff line change
@@ -53,22 +53,17 @@ class StimulusLazyControllerHandler {
5353
return;
5454
}
5555
new MutationObserver((mutationsList) => {
56-
for (const mutation of mutationsList) {
57-
switch (mutation.type) {
58-
case 'childList': {
59-
for (const node of mutation.addedNodes) {
60-
if (node instanceof Element) {
61-
extractControllerNamesFrom(node).forEach((controllerName) => {
62-
this.loadLazyController(controllerName);
63-
});
64-
}
56+
for (const { attributeName, target, type } of mutationsList) {
57+
switch (type) {
58+
case 'attributes': {
59+
if (attributeName === controllerAttribute &&
60+
target.getAttribute(controllerAttribute)) {
61+
extractControllerNamesFrom(target).forEach((controllerName) => this.loadLazyController(controllerName));
6562
}
6663
break;
6764
}
68-
case 'attributes': {
69-
if (mutation.attributeName === controllerAttribute) {
70-
extractControllerNamesFrom(mutation.target).forEach((controllerName) => this.loadLazyController(controllerName));
71-
}
65+
case 'childList': {
66+
this.lazyLoadExistingControllers(target);
7267
}
7368
}
7469
}

src/StimulusBundle/assets/src/loader.ts

+13-16
Original file line numberDiff line numberDiff line change
@@ -99,26 +99,23 @@ class StimulusLazyControllerHandler {
9999
return;
100100
}
101101
new MutationObserver((mutationsList) => {
102-
for (const mutation of mutationsList) {
103-
switch (mutation.type) {
104-
case 'childList': {
105-
// @ts-ignore
106-
for (const node of mutation.addedNodes) {
107-
if (node instanceof Element) {
108-
extractControllerNamesFrom(node).forEach((controllerName) => {
109-
this.loadLazyController(controllerName);
110-
});
111-
}
112-
}
113-
break;
114-
}
115-
102+
for (const { attributeName, target, type } of mutationsList) {
103+
switch (type) {
116104
case 'attributes': {
117-
if (mutation.attributeName === controllerAttribute) {
118-
extractControllerNamesFrom(mutation.target as Element).forEach((controllerName) =>
105+
if (
106+
attributeName === controllerAttribute &&
107+
(target as Element).getAttribute(controllerAttribute)
108+
) {
109+
extractControllerNamesFrom(target as Element).forEach((controllerName) =>
119110
this.loadLazyController(controllerName)
120111
);
121112
}
113+
114+
break;
115+
}
116+
117+
case 'childList': {
118+
this.lazyLoadExistingControllers(target as Element);
122119
}
123120
}
124121
}

0 commit comments

Comments
 (0)