Three ways to dynamically load CSS in JavaScript
If you have many related CSS files to load together, or want to load different CSS files dynamically, then the following methods will definitely help you.
The first type: generally used to load necessary files in external CSS files
The second: simply load an external CSS file in the page
The third type: use the createElement method to create a CSS Link tag
Here are a few functions that I used in the project before, I hope it will be useful to everyone!
The first type: generally used to load necessary files in external CSS files
The second: simply load an external CSS file in the page
The third type: use the createElement method to create a CSS Link tag
var head = document.getElementsByTagName('HEAD').item(0);
var style = document.createElement('link');
style.href = 'style.css';
style.rel = 'stylesheet';
style.type = 'text/css';
head.appendChild(style);
var style = document.createElement('link');
style.href = 'style.css';
style.rel = 'stylesheet';
style.type = 'text/css';
head.appendChild(style);
Here are a few functions that I used in the project before, I hope it will be useful to everyone!
function loadJs(file){ var scriptTag = document.getElementById('loadScript'); var head = document.getElementsByTagName('head').item(0); if(scriptTag) head.removeChild(scriptTag); script = document. createElement('script'); script.src = "../js/mi_"+file+".js"; script.type = 'text/javascript'; script.id = 'loadScript'; head.appendChild(script) ; } function loadCss(file){ var cssTag = document.getElementById('loadCss'); var head = document.getElementsByTagName('head').item(0); if(cssTag) head.removeChild(cssTag); css = document.createElement('link'); css.href = "../css/mi_"+file+".css";
css.rel = 'stylesheet';
css.type = 'text/css';
css.id = 'loadCss';
head.appendChild(css);
}
css.rel = 'stylesheet';
css.type = 'text/css';
css.id = 'loadCss';
head.appendChild(css);
}