I needed to change CSS stylesheets dynamically, and it is very easy, if you know how to do it. Just simple HTML and vanilla Javascript. No round trip to the server (no POST, no GET).
CodePen demo here: https://codepen.io/r-w-c/pen/yLrjGOM
Github demo page here: https://r-w-c.github.io/Switching-Stylesheets-without-roundtrip-to-server
Files here: https://github.com/R-W-C/Switching-Stylesheets-without-roundtrip-to-server
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamically load style sheet</title>
<link rel="stylesheet" href="css/main.css">
<link id="theme-link" rel="stylesheet" href="css/day.css">
</head>
<body>
<header>
<input type="radio" id="day-theme" name="theme" checked>Day theme</a>
<input type="radio" id="night-theme" name="theme">Night theme</a>
</header>
<main>
<div>Hello world!</div>
</main>
<script type="text/javascript">
document.querySelectorAll("input[name='theme']").forEach((input) => { input.addEventListener('change', setStyleSheetHref); });
function setStyleSheetHref(event)
{
document.getElementById('theme-link').setAttribute('href', event.target.id == 'day-theme' ? 'css/day.css' : 'css/night.css');
}
</script>
</body>
</html>
main.css:
main {
display: flex;
align-items: center;
justify-content: center;
width: 500px;
height: 500px;
margin: 120px;
border: 1px solid blue;
}
day.css:
main {
background-color: white;
color: black;
}
night.css:
main {
background-color: black;
color: white;
}