chore: Move liveReload code into script.

This commit is contained in:
Sidharth Vinod 2023-08-17 14:30:47 +05:30
parent fe1a06271a
commit 718d52a72c
No known key found for this signature in database
GPG Key ID: FB5CCD378D3907CD
4 changed files with 34 additions and 28 deletions

1
.gitignore vendored
View File

@ -46,3 +46,4 @@ stats/
demos/dev/**
!/demos/dev/example.html
!/demos/dev/reload.js

View File

@ -33,32 +33,6 @@ graph TB
el.innerHTML = svg;
</script>
<script>
// Set to false to disable live reload
const liveReload = true;
// Connect to the server and reload the page if the server sends a reload message
const connectToEvents = () => {
const events = new EventSource('/events');
const loadTime = Date.now();
events.onmessage = (event) => {
const time = JSON.parse(event.data);
if (time && time > loadTime) {
location.reload();
}
};
events.onerror = () => {
// No need to log this error, as it's not useful.
events.close();
// Try to reconnect after 1 second in case of errors
setTimeout(connectToEvents, 1000);
};
events.onopen = () => {
console.log('Connected to live reload server');
};
};
if (liveReload) {
setTimeout(connectToEvents, 1000);
}
</script>
<script src="/dev/reload.js"></script>
</body>
</html>

22
demos/dev/reload.js Normal file
View File

@ -0,0 +1,22 @@
// Connect to the server and reload the page if the server sends a reload message
const connectToEvents = () => {
const events = new EventSource('/events');
const loadTime = Date.now();
events.onmessage = (event) => {
const time = JSON.parse(event.data);
if (time && time > loadTime) {
location.reload();
}
};
events.onerror = (error) => {
console.error(error);
events.close();
// Try to reconnect after 1 second in case of errors
setTimeout(connectToEvents, 1000);
};
events.onopen = () => {
console.log('Connected to live reload server');
};
};
setTimeout(connectToEvents, 500);

View File

@ -5,5 +5,14 @@
// ensure that nobody can accidentally use this config for a build
"noEmit": true
},
"include": ["packages", "tests", "scripts", "cypress", "__mocks__", "./.eslintrc.cjs", "./*"]
"include": [
"packages",
"tests",
"scripts",
"cypress",
"__mocks__",
"./.eslintrc.cjs",
"./*",
"demos/dev"
]
}