Skip to content

Instantly share code, notes, and snippets.

@josephm28
Created March 18, 2019 12:55
Show Gist options
  • Save josephm28/1ea8185865c12e6477b373cbaf3eb4f3 to your computer and use it in GitHub Desktop.
Save josephm28/1ea8185865c12e6477b373cbaf3eb4f3 to your computer and use it in GitHub Desktop.
Load CSS Stylesheet if it's not loaded already. This is incredibly helpful to include in your JS modules, right above the class, as a way of importing the CSS file for the module without having to track it all in the main html page.
function loadCSSSheetIfNotLoaded({url}){
//Get the current stylesheets
const currentStyles = Object.values(document.styleSheets);
const foundSheet = currentStyles.find(sheet => sheet.href ? sheet.href.indexOf(url) != -1 : false);
if(!foundSheet){
//Didn't find the stylesheet, so let's add it
$(`<link href="${url}" rel="stylesheet">`).appendTo("head");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment