Skip to content

Commit

Permalink
Merge pull request #29 from bigskysoftware/sse-reconnection
Browse files Browse the repository at this point in the history
Improve SSE reconnection logic
  • Loading branch information
Renerick authored Jun 28, 2024
2 parents ba3d167 + d923e94 commit 9524ce5
Show file tree
Hide file tree
Showing 2 changed files with 280 additions and 19 deletions.
14 changes: 12 additions & 2 deletions src/sse/sse.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,15 +203,25 @@ This extension adds support for Server Sent Events to htmx. See /www/extensions
// Otherwise, try to reconnect the EventSource
if (source.readyState === EventSource.CLOSED) {
retryCount = retryCount || 0
var timeout = Math.random() * (2 ^ retryCount) * 500
retryCount = Math.max(Math.min(retryCount * 2, 128), 1)
var timeout = retryCount * 500
window.setTimeout(function() {
ensureEventSourceOnElement(elt, Math.min(7, retryCount + 1))
ensureEventSourceOnElement(elt, retryCount)
}, timeout)
}
}

source.onopen = function(evt) {
api.triggerEvent(elt, 'htmx:sseOpen', { source })

if (retryCount && retryCount > 0) {
const childrenToFix = elt.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]")
for (let i = 0; i < childrenToFix.length; i++) {
registerSSE(childrenToFix[i])
}
// We want to increase the reconnection delay for consecutive failed attempts only
retryCount = 0
}
}

api.getInternalData(elt).sseEventSource = source
Expand Down
Loading

0 comments on commit 9524ce5

Please sign in to comment.