Skip to content

Instantly share code, notes, and snippets.

@djalmajr
Created October 6, 2018 14:46
Show Gist options
  • Select an option

  • Save djalmajr/d4e32da7337263ff5be5e45793d29b61 to your computer and use it in GitHub Desktop.

Select an option

Save djalmajr/d4e32da7337263ff5be5e45793d29b61 to your computer and use it in GitHub Desktop.
DOM Helpers
(() => {
window.createElement = (name, attrs = {}) => {
const element = document.createElement(name);
Object.keys(attrs).forEach(key => (element[key] = attrs[key]));
return element;
};
window.loadStyle = href => {
return new Promise((onload, onerror) => {
const style = createElement("link", { onload, onerror, href, rel: "stylesheet" });
document.head.appendChild(style);
});
};
window.loadScript = src => {
return new Promise((onload, onerror) => {
const script = createElement("script", { onload, onerror, src });
document.head.appendChild(script);
});
};
if (window && !window["__dirname"]) {
const defProp = (name, get) => {
Object.defineProperty(window, name, { __proto__: null, get });
};
const stackTrace = () => {
const err = new Error().stack
.split("\n")
.filter(e => e)
.slice(-1)[0];
const regex = /(https?:\/\/.*):([0-9]+):([0-9]+)/;
const parts = err.match(regex) || [];
const { origin, pathname } = new URL(parts[1]);
const [file, ...dir] = pathname.split("/").reverse();
return {
line: parts[2],
column: parts[3],
origin: origin,
directory: dir.reverse().join("/"),
file: file
.split(".")
.slice(0, -1)
.join("."),
};
};
defProp("__stacktrace", stackTrace);
defProp("__dirname", () => stackTrace().directory);
defProp("__filename", () => stackTrace().file);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment