Fix styles refreshing issue with old styles still being there

master
Kuba Orlik 9 months ago
parent f91a0ce492
commit b46f59be2e

@ -39,19 +39,44 @@ export default function html(
${(navbar || default_navbar)(ctx)} ${body} ${(navbar || default_navbar)(ctx)} ${body}
${autoRefreshCSS ${autoRefreshCSS
? /* HTML */ `<script> ? /* HTML */ `<script>
function make_new_link() {
const new_link = document.createElement("link");
new_link.rel = "stylesheet";
new_link.href = \`/dist/main.css?\${Math.random()}+\${Math.random()}\`;
new_link.type = "text/css";
return new_link;
}
function getStyles() {
return Array.from(
document.querySelectorAll("head link")
).filter(
(e) => new URL(e.href).pathname == "/dist/main.css"
);
}
function refresh_css() { function refresh_css() {
Array.from(document.querySelectorAll("link")) const new_link = make_new_link();
.filter(
(e) => //only remove old css once the new one is loaded to prevent blink of unstyled content
new URL(e.href).pathname == "/dist/main.css" new_link.onload = () => {
) console.log("clearing styles");
.forEach((e) => { getStyles()
const url = new URL(e.href); .slice(0, -1)
url.search = .forEach((style) => {
"?" + Math.random() + "" + Math.random(); console.log({ style, new_link });
e.href = url.toString(); if (style !== new_link) {
}); style.parentElement.removeChild(style);
}
});
};
document.querySelector("head").appendChild(new_link);
} }
document.documentElement.addEventListener(
"turbo:morph",
refresh_css
);
const socket = new WebSocket("ws://localhost:60808"); const socket = new WebSocket("ws://localhost:60808");
socket.onmessage = refresh_css; socket.onmessage = refresh_css;
</script>` </script>`

Loading…
Cancel
Save