To replace CSS files on the fly with JavaScript typically involves dynamically changing the href
attribute of a <link>
element that references the CSS file.
To do this we can write something like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace CSS File on the Fly</title>
<link id="css-file" rel="stylesheet" type="text/css" href="original.css">
<script>
function replaceCSS(newCSSFile) {
// Get the <link> element that references the CSS file
const cssLink = document.getElementById('css-file');
// Create a new <link> element
const newLink = document.createElement('link');
newLink.rel = 'stylesheet';
newLink.type = 'text/css';
newLink.href = newCSSFile;
// Replace the old <link> element with the new one
cssLink.parentNode.replaceChild(newLink, cssLink);
}
</script>
</head>
<body>
<button onclick="replaceCSS('new.css')">Replace CSS</button>
</body>
</html>
In this example:
There’s a button in the body that, when clicked, calls the replaceCSS()
function with the path to the new CSS file as an argument.
The replaceCSS()
function retrieves the existing <link>
element that references the CSS file by its ID (css-file)
.
It creates a new <link>
element with the provided path to the new CSS file.
It replaces the existing <link>
element with the new one using the parentNode.replaceChild()
method.
This approach allows you to dynamically replace CSS files on the fly using JavaScript. Keep in mind that replacing CSS files in this way may cause some flickering or re-rendering of the page as the new styles are applied.