htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Functions in Scripts Do Not Run Automatically When Script is a Module

Open josephetareh opened this issue 1 year ago • 2 comments

I am not sure if anyone else is experiencing this issue but when a script with type="module" is included in a swap, any function that is generally called in that script does not automatically run. I know that this behaviour is generally solved with an event listener for now, but I wonder if there is a reason for this type of behaviour.

By this I mean, if you have this code:

<div id="swapped-content">Hi there</div>
<script src="path/to/script/test-script.js></script>

test-script.js

function testHi(){
    console.log("test-hi")
}
testHi()

In this case, after the swap, test-hi is printed in this console after the swap occurs. But then if I add type="module" to the script:

<div id="swapped-content">Hi there</div>
<script src="path/to/script/test-script.js" type="module"></script>

test-script.js

function testHi(){
    console.log("test-hi")
}
testHi()

In this case, test-hi is not printed and nothing is actually printed to the console. This is despite the fact that I can see that htmx has picked up the script. Any additional voices on the best pattern for this kind of behaviour would be greatly appreciated.

josephetareh avatar Jun 19 '24 11:06 josephetareh

+1 for this

bgr11n avatar Jul 13 '24 14:07 bgr11n

I don't get the same behavior when trying to reproduce this (I've tried several htmx versions). Because it's a self-contained module, it only runs the first time I reference it, which I think is standard browser behavior.

If I do an inline module then the browser will run it every time as it has no name to distinguish it:

<div id="swapped-content">Hi there</div>
<script type="module">
    function testHi(){
        console.log("test-hi")
    }
    testHi()
</script>

scrhartley avatar Jun 11 '25 14:06 scrhartley