fix: head-support race condition #2599
Description
currently the head-support feature starts doing its merging based off an htmx:afterSwap event. This means that any script being loaded into the DOM from the htmxSwap that wants to run some initialisation code may run after the htmx:afterHeadMerge event has triggered, and never see it.
An example for this would be if you want to return a ChartJS from an endpoint along with the script to display the chart.
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<canvas id="myChart"></canvas>
<script>
htmx.on('htmx:afterHeadMerge', function () {
(async () => {
while (!Chart) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, { <CONFIG> });
})();
});
</script>
The polling is necessary to check that the Chart class has been declared (i.e. the new head script has loaded)
(and yes this could do with a timeout so it doesn't try for ever, but this is the basic solution)
However, this code won't work every time if we have htmx:afterSwap in head-support.js as the trigger.
Changing htmx:afterSwap to htmx:afterSettle ensures the DOM has settled (i.e. our event listener has been registered) before the head swap functionality is performed and our code works as expected.
Testing
This was tested with the above code by calling this code on a lazy-loaded hx-post. The race condition seems to be gone.
Checklist
- [x] I have read the contribution guidelines
- [x] I have targeted this PR against the correct branch (
masterfor website changes,devfor source changes) - [x] This is either a bugfix, a documentation update, or a new feature that has been explicitly approved via an issue
- [x] I ran the test suite locally (
npm run test) and verified that it succeeded
Hello, please note that for htmx 2 (aka the dev branch here), we moved extensions to a separate repository.
So you'll want to either retarget this PR to the v1 branch, in the extension's src directory, or port this PR to the new extensions repo (you may want to check that htmx 2 + the v2 extension doesn't already solve this btw)
Yep, please retarget against v1 and the new extensions repo. Thank you!
Hey stu checking in here, can you retarget the v1 branch and port the change over to the new extensions repo?
Hey stu checking in here, can you retarget the
v1branch and port the change over to the new extensions repo?
Apologies, totally forgot to see this through.
Opened a new PR on the other branch: https://github.com/bigskysoftware/htmx/pull/2704
And also in the new htmx-extensions repo: https://github.com/bigskysoftware/htmx-extensions/pull/45