Skip to content

Instantly share code, notes, and snippets.

@mayank99
Created December 12, 2023 04:29
Show Gist options
  • Save mayank99/4e0c030ce7f9d04cdad129bff1dd5b20 to your computer and use it in GitHub Desktop.
Save mayank99/4e0c030ce7f9d04cdad129bff1dd5b20 to your computer and use it in GitHub Desktop.
import attributes polyfill
async function importCss(url) {
try {
return await (new Function(`return import("${url}", { with: { type: "css" } })`))();
} catch {
try {
return await (new Function(`return import("${url}", { assert: { type: "css" } })`))();
} catch {
return fetch(url).then(res => res.text()).then(cssText => {
const stylesheet = new CSSStyleSheet();
stylesheet.replaceSync(cssText);
return { default: stylesheet };
});
}
}
}
// usage:
// const css = await importCss('https://unpkg.com/open-props');
// document.adoptedStyleSheets = [...document.adoptedStyleSheets, css.default];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment