We’re followers of Customized Parts round right here. Their design makes them significantly amenable to lazy loading, which is usually a boon for efficiency.
Impressed by a colleague’s experiments, I just lately set about writing a easy auto-loader: Each time a {custom} aspect seems within the DOM, we wanna load the corresponding implementation if it’s not obtainable but. The browser then takes care of upgrading such components from there on out.
Likelihood is you received’t really need all this; there’s normally a less complicated method. Used intentionally, the methods proven right here would possibly nonetheless be a helpful addition to your toolset.
For consistency, we wish our auto-loader to be a {custom} aspect as properly — which additionally means we are able to simply configure it through HTML. However first, let’s determine these unresolved {custom} components, step-by-step:
class AutoLoader extends HTMLElement {
connectedCallback() {
let scope = this.parentNode;
this.uncover(scope);
}
}
customElements.outline(“ce-autoloader”, AutoLoader);
Assuming we’ve loaded this module up-front (utilizing async is right), we are able to drop a <ce-autoloader> aspect into the <physique> of our doc. That may instantly begin the invention course of for all little one components of <physique>, which now constitutes our root aspect. We might restrict discovery to a subtree of our doc by including <ce-autoloader> to the respective container aspect as a substitute — certainly, we’d even have a number of cases for various subtrees.
In fact, we nonetheless need to implement that uncover technique (as a part of the AutoLoader class above):
uncover(scope) {
let candidates = [scope, …scope.querySelectorAll(“*”)];
for(let el of candidates) {
let tag = el.localName;
if(tag.consists of(“-“) && !customElements.get(tag)) {
this.load(tag);
}
}
}
Right here we examine our root aspect together with each single descendant (*). If it’s a {custom} aspect — as indicated by hyphenated tags — however not but upgraded, we’ll try and load the corresponding definition. Querying the DOM that means is perhaps costly, so we must be just a little cautious. We are able to alleviate load on the primary thread by deferring this work:
connectedCallback() {
let scope = this.parentNode;
requestIdleCallback(() => {
this.uncover(scope);
});
}
requestIdleCallback isn’t universally supported but, however we are able to use requestAnimationFrame as a fallback:
let defer = window.requestIdleCallback || requestAnimationFrame;
class AutoLoader extends HTMLElement {
connectedCallback() {
let scope = this.parentNode;
defer(() => {
this.uncover(scope);
});
}
// …
}
Now we are able to transfer on to implementing the lacking load technique to dynamically inject a <script> aspect:
load(tag) {
let el = doc.createElement(“script”);
let res = new Promise((resolve, reject) => {
el.addEventListener(“load”, ev => {
resolve(null);
});
el.addEventListener(“error”, ev => {
reject(new Error(“did not find custom-element definition”));
});
});
el.src = this.elementURL(tag);
doc.head.appendChild(el);
return res;
}
elementURL(tag) {
return `${this.rootDir}/${tag}.js`;
}
Notice the hard-coded conference in elementURL. The src attribute’s URL assumes there’s a listing the place all {custom} aspect definitions reside (e.g. <my-widget> → /parts/my-widget.js). We might provide you with extra elaborate methods, however that is ok for our functions. Relegating this URL to a separate technique permits for project-specific subclassing when wanted:
class FancyLoader extends AutoLoader {
elementURL(tag) {
// fancy logic
}
}
Both means, be aware that we’re counting on this.rootDir. That is the place the aforementioned configurability is available in. Let’s add a corresponding getter:
get rootDir() {
let uri = this.getAttribute(“root-dir”);
if(!uri) {
throw new Error(“can’t auto-load {custom} components: lacking `root-dir`”);
}
if(uri.endsWith(“/”)) { // take away trailing slash
return uri.substring(0, uri.size – 1);
}
return uri;
}
You is perhaps pondering of observedAttributes now, however that doesn’t actually make issues simpler. Plus updating root-dir at runtime looks as if one thing we’re by no means going to want.
Now we are able to — and should — configure our components listing: <ce-autoloader root-dir=”/parts”>.
With this, our auto-loader can do its job. Besides it solely works as soon as, for components that exist already when the auto-loader is initialized. We’ll most likely need to account for dynamically added components as properly. That’s the place MutationObserver comes into play:
connectedCallback() {
let scope = this.parentNode;
defer(() => {
this.uncover(scope);
});
let observer = this._observer = new MutationObserver(mutations => {
for(let { addedNodes } of mutations) {
for(let node of addedNodes) {
defer(() => {
this.uncover(node);
});
}
}
});
observer.observe(scope, { subtree: true, childList: true });
}
disconnectedCallback() {
this._observer.disconnect();
}
This fashion, the browser notifies us every time a brand new aspect seems within the DOM — or reasonably, our respective subtree — which we then use to restart the invention course of. (You would possibly argue we’re re-inventing {custom} components right here, and also you’d be form of appropriate.)
Our auto-loader is now totally useful. Future enhancements would possibly look into potential race situations and examine optimizations. However likelihood is that is ok for many situations. Let me know within the feedback you probably have a special method and we are able to examine notes!
An Strategy to Lazy Loading Customized Parts initially revealed on CSS-Tips, which is a part of the DigitalOcean household. It is best to get the e-newsletter.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!