timely binding for time-sensitive event

I have a video tag which I need to bind the ondataloaded event. Stimulus bind successfully most of the time but failed to bind the event before it is fired the other time. I guess this is due to the asynchronous nature between page loading and javascript executing. Wonder if there is a way around this?

How about these two tactics:

  • inject the video element on connect() in the stimulus controller. This will let you control the timing.
  • add preload="false" to the video element and manually start the preload on connect() in the stimulus controller. But I’m not sure how to re-enable the preload and it’s also worth noting that this preload attribute is “merely a hint” to the browser as to the best user experience.

One way you can inject the video element is by wrapping your server-generated html inside a <template> element (which will make it not render by default) that you then move to another spot (e.g. a designated wrapper) within your stimulus-controlled element on connect()

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = [ "videoTemplate", "videoWrapper"]

  connect() {
    this.injectVideoIntoWrapper()
  }

  injectVideoIntoWrapper() {
    if (!this.hasVideoTemplateTarget || !this.hasVideoWrapperTarget) { return }
    this.videoWrapperTarget.append(this.videoTemplateTarget)
  }
}
1 Like

Thanks. The template solution is a usable workaround.

1 Like