I was originally using this code to link in my stimulus controllers:
window.Stimulus = Application.start()
const context = require.context("../src/controllers", true, /\.js$/)
Stimulus.load(definitionsFromContext(context))
However, one of the controllers loads the google maps api. I do not want to do that on every page. So now I am trying to load only the controllers needed for a page. So I am doing this in my DOMContentLoaded event:
// Load any stimulus controllers for this page
const controllerElements = document.querySelectorAll('[data-controller]');
// Extract unique controller names
const uniqueControllers = new Set();
controllerElements.forEach((element) => {
const controllers = element.dataset.controller.split(' ');
controllers.forEach((controller) => uniqueControllers.add(controller.replaceAll('-','_')));
});
uniqueControllers.forEach((controllerName) => {
console.log("loading controller: ", controllerName);
import(`../src/controllers/${controllerName}_controller.js`).then((module) => {
const controllerDefinition = module.default;
window.Stimulus.register(controllerName, controllerDefinition);
});
});
It seems like the controllers are being loaded properly. But none of my connect methods are being reached and none of my actions are being fired.
What am I doing wrong? Is there a better way to load individual controllers? What would happen if I loaded a turbo-frame on the page and the content of the turbo frame had more controllers to connect?
Any help would be greatly appreciated. TIA!