Skip to content

Instantly share code, notes, and snippets.

@ahmu83
Created September 20, 2023 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmu83/b31f8ccfe5e35a994d7b41fef558cecf to your computer and use it in GitHub Desktop.
Save ahmu83/b31f8ccfe5e35a994d7b41fef558cecf to your computer and use it in GitHub Desktop.
Dynamic Style Enqueuing for the DOM
/**
* Enqueue styles dynamically into DOM.
* Example usage
*
* enqueueStyle({
* 'splide-styles': {
* url: 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css',
* },
* });
*
* @param Object styles Styles object
* @return Void
*/
function enqueueStyle(styles) {
var key, key2, style, styleId, styleUrl, styleMedia, styleElem, styleExists, stylesLength, stylesLoaded, styleAttributes;
for (key in styles) {
if (typeof styles[key].id === 'undefined') {
styles[key].id = key;
}
style = styles[key];
styleId = style.id;
styleUrl = style.url;
styleMedia = style.media ? style.media : 'all';
styleAttributes = typeof style.attributes === 'undefined' ? {} : style.attributes;
styleExists = document.querySelector('style#' + styleId);
if ( !styleExists ) {
styleElem = document.createElement('link');
styleElem.id = styleId;
styleElem.rel = 'stylesheet';
styleElem.type = 'text/css';
styleElem.media = 'all';
styleElem.href = styleUrl;
for (key2 in styleAttributes) {
styleElem[key2] = styleAttributes[key2];
}
if (document.head) {
document.head.appendChild(styleElem);
} else if (document.body) {
document.body.appendChild(styleElem);
} else {
return; // no place to add the style
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment