Skip to content

Commit 431ecc9

Browse files
committed
refactor: headstart initialization
1 parent 2d962b2 commit 431ecc9

1 file changed

Lines changed: 28 additions & 10 deletions

File tree

server/services/snapshot/headstart_snapshot.php

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,22 +27,40 @@
2727
data_config.options = options_<?php echo htmlspecialchars($_GET['service']); ?>.dropdowns;
2828
}
2929
</script>
30+
3031
<?php include "../../../dist/headstart.php"; ?>
32+
33+
<!-- The script below attempts to launch headstart by calling its start method.
34+
However, because headstart loads asynchronously, it is necessary to wait some time. -->
3135
<script type="text/javascript">
32-
// Function to check if headstart is loaded and start it
36+
const DELAY_BETWEEN_ATTEMPTS_MS = 250;
37+
const LIMIT_OF_ATTEMPTS = 10;
38+
let numberOfAttempts = 0;
39+
40+
function checkThatInitializeMethodReady() {
41+
return typeof headstart === "object" && typeof headstart.start === "function";
42+
}
43+
3344
function initializeHeadstart() {
34-
if (typeof headstart !== 'undefined' && headstart.start) {
45+
if (checkThatInitializeMethodReady()) {
3546
headstart.start();
36-
} else {
37-
setTimeout(initializeHeadstart, 100);
47+
return;
3848
}
49+
50+
if (numberOfAttempts < LIMIT_OF_ATTEMPTS) {
51+
let timerId = setTimeout(() => {
52+
clearTimeout(timerId);
53+
numberOfAttempts += 1;
54+
initializeHeadstart();
55+
}, DELAY_BETWEEN_ATTEMPTS_MS);
56+
57+
return;
58+
}
59+
60+
console.error("Unable to load headstart or its start method is not a function!");
3961
}
40-
41-
// Wait for DOM to be ready, then start checking for headstart
42-
document.addEventListener('DOMContentLoaded', function() {
43-
// Give a small delay to ensure deferred scripts have time to load
44-
setTimeout(initializeHeadstart, 500);
45-
});
62+
63+
document.addEventListener("DOMContentLoaded", initializeHeadstart);
4664
</script>
4765
</body>
4866
</html>

0 commit comments

Comments
 (0)