Is it safe to stop and start stimulus?

I was just adding stimulus to an old project and ran in to a bit of a performance issue. The application has a number of pages where we use d3 to draw SVG charts from JSON time series data. The JSON data is loaded by an XHR call when the page loads so there’s a short delay between the initial page render and the chart appearing.

The problem I have is that all the DOM insertion that d3 does to draw the chart results in lots of work for stimulus processing the mutations. In the Chrome profiler I see about 120ms in “Run Microtasks” immediately following our chart drawing code. It’s enough added to the existing delay that it’s quite noticeable.

Longer term I’d like to rework the code, but my short term fix is to suspend stimulus’s mutation observers for the period while we’re drawing the chart - something like this:

if (window.stimulus) {
  window.stimulus.stop();
}
// Original drawing code
if (window.stimulus) {
  window.stimulus.start();
}

(window.stimulus holds the return value from Application.start())

I don’t see these methods documented, but they seem to be doing what I need. Could someone who knows the code better comment on whether this might cause any issues as I start to lean on stimulus more on these pages? Is this a corner case that might be worth documenting?

-Mark.

1 Like

Does the d3 script generate a few mutation events or many mutations events. If many, what if you applied the d3 script to a virtual DOM element and then added the completed virtual element to the primary DOM. Does this help your performance?