Skip to content

Instantly share code, notes, and snippets.

@nuxodin
Last active June 10, 2019 18:02
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 nuxodin/b0dfcf3a1d5b35d448032e67eb0005a6 to your computer and use it in GitHub Desktop.
Save nuxodin/b0dfcf3a1d5b35d448032e67eb0005a6 to your computer and use it in GitHub Desktop.
CSS Import function. Loads a CSS file relative to the script where the function was called! (like js-module imports)
c1CssImport = function (location) { // todo: handle absolute urls
const e = new Error();
const calledFile = e.stack.split('\n')[2].match(/[a-z]+:[^:]+/);
const calledUrl = new URL(calledFile);
calledUrl.search = '';
const target = new URL(location, calledUrl).toString();
for (let el of document.querySelectorAll('link[rel=stylesheet]')) {
if (el.href === target) return; // already loaded
}
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = target;
document.head.append(link);
// todo: return a promise
}
@nuxodin
Copy link
Author

nuxodin commented Jun 10, 2019

Ussage:
file: dialog/main.js

c1CssImport('./ui.css'); // loads dialog/main.css if not already loaded
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment