How to Load CSS File Dynamically

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



Leave a reply



Submit