Very late to the party, but since this got many views already, I’ll leave a reference for those landing here in the future – myself included.
I used to embed some arbitrary JS code like the OP into a LiveView, also with some side effects. Works apparently okay on the first render, but doesn’t work if live navigating back to the page.
I think the solution is as @LostKobrakai said in Re-render JS on a Live view update - how to? - #2 by LostKobrakai, either using JS events or hooks: