How to load/unload css dynamically
Hope this help you.
function injectCss(styles) {
let styleSheet = document.createElement("style");
styleSheet.type = 'text/css';
styleSheet.setAttribute("id", "dunamicstylesheet");
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);
}
//Create-styleSheet
injectCss('dynamic.css');
//remove-styleSheet
var stylesheet = document.getElementById('dunamicstylesheet');
stylesheet.parentNode.removeChild(stylesheet);
Dynamically load stylesheets
You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.
JavaScript
(function(){
var styles = document.createElement('link');
styles.rel = 'stylesheet';
styles.type = 'text/css';
styles.media = 'screen';
styles.href = 'path/to/css/file';
document.getElementsByTagName('head')[0].appendChild(styles);
})();
Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a <head>
tag in your html.
Related Topics
Selecting an Element That Doesn't Have a Child with a Certain Class
Tools Debugging CSS in Internet Explorer
Is It Ok to Use Cellpadding="2" Cellspacing="2" in <Table>
CSS Perspective Not Working in Firefox
Can Relative Paths Be Used for @Font-Face Src
How to Style the Default Wordpress Audio Player with CSS
Adding CSS Border Changes Positioning in HTML5 Webpage
Resizing CSS Custom Mouse Cursor
Does a Cache Buster on an Image Url in CSS Cause an Extra Request
How to Force Inline-Block Elements to Wrap
Using Position:Absolute to Set an Inputs Width
Give a CSS Styled Div a "Border-Left-Image"
Css: Scale Background Image Down If Larger Than Window, Keep at 100% Otherwise
How to Overflow the Contents of a Column into the Next Column Using CSS