Skip to content

Commit b541379

Browse files
authored
Merge pull request #652 from AnswerDotAI/reload_refactor
Refactored live reload js
2 parents 7737c91 + 9213078 commit b541379

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

fasthtml/live_reload.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,24 @@
33

44
__all__ = ["FastHTMLWithLiveReload"]
55

6-
7-
def LiveReloadJs(reload_attempts:int=1, reload_interval:float=1000., **kwargs):
6+
def LiveReloadJs(reload_attempts:int=20, reload_interval:int=1000, **kwargs):
87
src = """
9-
(function() {
10-
var socket = new WebSocket(`ws://${window.location.host}/live-reload`);
11-
var maxReloadAttempts = %s;
12-
var reloadInterval = %s; // time between reload attempts in ms
13-
socket.onclose = function() {
14-
let reloadAttempts = 0;
15-
const intervalFn = setInterval(function(){
16-
window.location.reload();
17-
reloadAttempts++;
18-
if (reloadAttempts === maxReloadAttempts) clearInterval(intervalFn);
19-
}, reloadInterval);
20-
}
8+
(() => {
9+
let attempts = 0;
10+
const connect = () => {
11+
const socket = new WebSocket(`ws://${window.location.host}/live-reload`);
12+
socket.onopen = async() => {
13+
const res = await fetch(window.location.href);
14+
if (res.ok) {
15+
attempts ? window.location.reload() : console.log('LiveReload connected');
16+
}};
17+
socket.onclose = () => {
18+
!attempts++ ? connect() : setTimeout(() => { connect() }, %d);
19+
if (attempts > %d) window.location.reload();
20+
}};
21+
connect();
2122
})();
22-
"""
23+
"""
2324
return Script(src % (reload_attempts, reload_interval))
2425

2526
async def live_reload_ws(websocket): await websocket.accept()
@@ -52,4 +53,4 @@ def __init__(self, *args, **kwargs):
5253
# "hdrs" and "routes" can be missing, None, a list or a tuple.
5354
kwargs["hdrs"] = [*(kwargs.get("hdrs") or []), LiveReloadJs(**kwargs)]
5455
kwargs["routes"] = [*(kwargs.get("routes") or []), WebSocketRoute("/live-reload", endpoint=live_reload_ws)]
55-
super().__init__(*args, **kwargs)
56+
super().__init__(*args, **kwargs)

0 commit comments

Comments
 (0)