by Ciantic · 4y ago · 0 comments
If you haven't keeping up with all the new script-tag parameters, I suggest looking at this: https://gist.github.com/jakub-g/385ee6b41085303a53ad92c7c8af...
Choosing type=module is usually better choice than classic script tags like in the article. Module tags fetches (if any modules is used) asynchronously, and executes after the parser, however it won't work with older browsers.
const $ = sel => [...document.querySelectorAll(sel)];
But then you get to it and are adding a lot of classes, so you might add a couple of helper methods: const addClass = (col, cls) => col.forEach(el => el.classList.add(cls));
const removeClass = (col, cls) => col.forEach(el => el.classList.remove(cls));
addClass($('ul li'), 'list-item');
Oh and you might need to inject content before/after, that's a bit trickier but thanks to the classic You Might Not Need jQuery[1] we know how to do it: const insertBefore = (col, html) => col.forEach(el => el.insertAdjacentElement('beforebegin', html));
const insertAfter = (col, html) => col.forEach(el => el.insertAdjacentElement('afterend', html));
insertAfter($('ul li:last-child'), 'New todo item');
Keep going a bit like that, until you realize you are basically reinventing jQuery but pretty badly, undocumented, and untested.Add a couple of very nice-to-haves, like chaining (instead of nesting in these examples above) and prototypes and that's what Umbrella JS is, very thin methods to manipulate the DOM and handle events. In fact, compare our "addClass" implementation in this comment to Umbrella's addClass[2], it's almost the same size but hundred times more flexible:
// Add class(es) to the matched nodes
u.prototype.addClass = function () {
return this.eacharg(arguments, function (el, name) {
el.classList.add(name);
});
};
[1] https://youmightnotneedjquery.com/[2] https://github.com/franciscop/umbrella/blob/master/src/plugi...
export function each(qs, cb) {
if (typeof qs === "string") {
qs = document.querySelectorAll(qs);
}
if (!qs) {
return;
}
if (qs.length === undefined) {
qs = [qs];
}
for (var i = 0; i < qs.length; i++) {
cb(qs[i], i);
}
}
export function on(ev, qs, cb) {
let cancelFns = [];
each(qs, (el) => {
el.addEventListener(ev, cb);
cancelFns.push(() => {
el.removeEventListener(ev, cb);
});
});
return () => {
cancelFns.forEach((fn) => {
fn();
});
};
}script type="module" src="module.js"
script nomodule src="nomodule.js"
Also it provide some kind of JS hijack. All the code with in the module can be tainted by a random .js included elsewhere in the page. However code in module can still access the window object to have access to global and the dom.