Skip to content

Instantly share code, notes, and snippets.

@Torthu
Created January 18, 2021 10:04
Show Gist options
  • Save Torthu/202f87411449600d46c6a841885b4880 to your computer and use it in GitHub Desktop.
Save Torthu/202f87411449600d46c6a841885b4880 to your computer and use it in GitHub Desktop.
Set stylesheet from css
/**
* Appends a stylesheet to document.body (<link rel="stylesheet" type="text/css" href="some-url" />)
* @param stylesheetUrl String URL to stylesheet
* @param cacheBust Function Rand-function that creates a string that will be appended to the stylesheet url to bust browser caching
* @return void
*/
const setStylesheetDynamically = (stylesheetUrl: string, cacheBust?: () => string): void => {
const stylesheet = document.createElement("link");
stylesheet.setAttribute("rel", "stylesheet");
stylesheet.setAttribute("type", "text/css");
const append = `${cacheBust ? `?bust=${cacheBust()}` : ""}`;
stylesheet.setAttribute(
"href",
`${stylesheetUrl}${append}`
);
document.body.appendChild(stylesheet);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment