htmx icon indicating copy to clipboard operation
htmx copied to clipboard

JavaScript code in <script> tag being run twice in Chrome and Edge, but not Firefox

Open glenvaughan opened this issue 2 years ago • 5 comments

If my HTML response contains a <script> tag, like the following...

<script>
    console.log('this is running');
</script>

...once the content is loaded into the DOM, the console.log() statement will fire twice in Chrome and Edge. I've confirmed that the script tag and its contents only appear once in the DOM, but the log appears twice in the console.

The console shows that the calls are coming from two different files, named like VM1683 and VM1685 (the numbers change, but they always start with VM, and the numbers on the two files are always slightly different from each other).

This happens in both Chrome and Edge, but not in Firefox.

glenvaughan avatar Jan 28 '23 02:01 glenvaughan

Any new info on this?

paulik123 avatar May 03 '23 10:05 paulik123

I've found out the Chromium based browsers evaluate the script tags if using the insertBefore() method. In the insertNodesBefore() function of htmx: console.log("BEFORE INSERT BEFORE", child) parentNode.insertBefore(child, insertBefore); console.log("AFTER INSERT BEFORE", child)

Running on chrome gives me the output: image

While running on Firefox gives me: image

EDIT: After a long time debugging I've found out that this only happens if useTemplateFragments is set to true.

paulik123 avatar May 03 '23 11:05 paulik123

I'd love to hear about an update on this. I just ran into it today. I need useTemplateFragements to deal with replacing table rows + an oob swap in the same request in multiple places but also have htmx responses which return <script> tags and not all of them can be made ok to execute twice.

jmichalicek avatar Aug 08 '23 19:08 jmichalicek

Same with me, and having trouble because of the same use case of @jmichalicek

D1360-64RC14 avatar Oct 05 '23 15:10 D1360-64RC14

EDIT: After a long time debugging I've found out that this only happens if useTemplateFragments is set to true.

I have the same issue. I return table rows, with additional swap-oob content along for the ride. Therefore useTemplateFragments needs to be true.

All included JS also runs twice. Tolerable sometimes, but I now have a case where it isn't, and I can't workaround it.

netadapt avatar Feb 28 '24 09:02 netadapt

I am having an error where when i click on a div it is clicked 2 times and in this i have added a js file to public folder and i have used ejs

Tarun-Behera avatar Mar 16 '24 19:03 Tarun-Behera

Hey, do you see it still happening in htmx 1.9.11 ?

Telroshan avatar Mar 17 '24 19:03 Telroshan

Hey, do you see it still happening in htmx 1.9.11 ?

I just upgraded to 1.9.11 and revisited this - the issue is now resolved.

Thank you very much @Telroshan - I was worried this issue has been buried, so very pleased to see the fix.

netadapt avatar Mar 18 '24 09:03 netadapt