Hotwire Discussion

Injected javascript loaded after turbo:load

Hi,

I’m adding a new javascript library to the head of a particular page as I don’t want it on all pages (as it’s rather large). The handbook says that this is supported.

However, while the script tag is injected in to the head correctly, the replacement of the body (by turbo drive) is executed immediately and, therefore, the script has not been loaded at this point (as it would be if you simply loaded the page without turbo).

Furthermore, the turbo:load event is fired before the script has finished loading as well, so I can’t use that either.

I can, of course, wait for the load event of the particular script to fire but this seems like something turbo should handle for me? I think mirroring the way the standard page model works as closely as possible would make this easier for everyone? Could you, for example, automatically add load event listeners to injected scripts and wait for them (when not defer or async) to load before updating the html and then triggering the turbo:load event? This would also help with Stimulus controllers which are mutationobserver based (and get initialised before the turbo:load) event as well?