Created
September 20, 2023 16:52
-
-
Save ahmu83/b31f8ccfe5e35a994d7b41fef558cecf to your computer and use it in GitHub Desktop.
Dynamic Style Enqueuing for the DOM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Enqueue styles dynamically into DOM. | |
* Example usage | |
* | |
* enqueueStyle({ | |
* 'splide-styles': { | |
* url: 'https://cdn.jsdelivr.net/npm/@splidejs/[email protected]/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