In some cases external CSS files needed to be loaded "on demand" rather than including them in the initial HTML markup. In such cases you can use write Javascript code to load the file dynamically.
Creating a new <link> Element
CSS files are referenced by <link> tag in HTML. You can create such a tag with Javascript and append it to the page's HTML.
// create new link tag
var link = document.createElement('link');
// set properties of link tag
link.href = 'css-file.css';
link.rel = 'stylesheet';
link.type = 'text/css';
// Loaded successfully
link.onload = function() {
console.log('success');
};
// Loading failed
link.onerror = function() {
console.log('error');
};
// append link element to html
document.body.appendChild(link);
Other things to note :
- CSS files can be loaded from same or different domain
- onload and onerror events on the link element can be used to check whether CSS files was loaded successfully or not.