Geraldlzc it should execute everytime the post component is recreated ("oncreate"), or everytime a preview is updated. It's not supposed to execute on post "onupdate" however.
Without describing exactly how you loaded and interacted with the page, it's impossible to say whether what happens is expected or not.
Generally, it's a good idea to not have the javascript in the template. You have more flexibility by creating a static template and use the extension API to add javascript features to Flarum. For example Mentions has a very cool UI integration, yet the template doesn't have any javascript as part of the template (it does have a bit of javascript to set attributes on the template during previews though)