Dynamically Loading CSS

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.

How to load/unload css dynamically

Try this:

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 loading css file using javascript with callback without jQuery

Unfortunately there is no onload support for stylesheets in most modern browsers. There is a solution I found with a little Googling.

Cited from: http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof

The basics

The most basic implementation of this can be done in a measely 30 lines of — framework independent — JavaScript code:

function loadStyleSheet( path, fn, scope ) {
var head = document.getElementsByTagName( 'head' )[0], // reference to document.head for appending/ removing link nodes
link = document.createElement( 'link' ); // create the link node
link.setAttribute( 'href', path );
link.setAttribute( 'rel', 'stylesheet' );
link.setAttribute( 'type', 'text/css' );

var sheet, cssRules;
// get the correct properties to check for depending on the browser
if ( 'sheet' in link ) {
sheet = 'sheet'; cssRules = 'cssRules';
}
else {
sheet = 'styleSheet'; cssRules = 'rules';
}

var interval_id = setInterval( function() { // start checking whether the style sheet has successfully loaded
try {
if ( link[sheet] && link[sheet][cssRules].length ) { // SUCCESS! our style sheet has loaded
clearInterval( interval_id ); // clear the counters
clearTimeout( timeout_id );
fn.call( scope || window, true, link ); // fire the callback with success == true
}
} catch( e ) {} finally {}
}, 10 ), // how often to check if the stylesheet is loaded
timeout_id = setTimeout( function() { // start counting down till fail
clearInterval( interval_id ); // clear the counters
clearTimeout( timeout_id );
head.removeChild( link ); // since the style sheet didn't load, remove the link node from the DOM
fn.call( scope || window, false, link ); // fire the callback with success == false
}, 15000 ); // how long to wait before failing

head.appendChild( link ); // insert the link node into the DOM and start loading the style sheet

return link; // return the link node;
}

This would allow you to load a style sheet with an onload callback function like this:

loadStyleSheet( '/path/to/my/stylesheet.css', function( success, link ) {
if ( success ) {
// code to execute if the style sheet was loaded successfully
}
else {
// code to execute if the style sheet failed to successfully
}
} );

Or if you want to your callback to maintain its scope/ context, you could do something kind of like this:

loadStyleSheet( '/path/to/my/stylesheet.css', this.onComplete, this );

Dynamically load .css based on condition in reactJS application

Easy - i've delt with similar before.

componentWillMount() {
if(this.props.css1 === true) {
require('style1.css');
} else {
require('style2.css');
}

}

How to dynamically load CSS with Angular

You can put your additionals .css in the folder assets (and remove from angular.json)

Then the only change is add the "assets" folder to the href

  loadStyle(styleName: string) {
const head = this.document.getElementsByTagName('head')[0];

let themeLink = this.document.getElementById(
'client-theme'
) as HTMLLinkElement;
if (themeLink) {
themeLink.href = `assets/${styleName}`; //<--add assets
} else {
const style = this.document.createElement('link');
style.id = 'client-theme';
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = `assets/${styleName}`; //<--add assets

head.appendChild(style);
}
}

a stackblitz



Related Topics



Leave a reply



Submit