Saturday, July 27, 2024

An Strategy to Lazy Loading Customized Components | CSS-Methods

[ad_1]

We’re followers of Customized Components round right here. Their design makes them significantly amenable to lazy loading, which generally is a boon for efficiency.

Impressed by a colleague’s experiments, I just lately set about writing a easy auto-loader: Each time a {custom} factor seems within the DOM, we wanna load the corresponding implementation if it’s not out there but. The browser then takes care of upgrading such components from there on out.

Likelihood is you gained’t really want all this; there’s normally a less complicated method. Used intentionally, the strategies proven right here may nonetheless be a helpful addition to your toolset.

For consistency, we would like our auto-loader to be a {custom} factor as effectively — which additionally means we are able to simply configure it by way of 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> factor into the <physique> of our doc. That can instantly begin the invention course of for all youngster components of <physique>, which now constitutes our root factor. We may restrict discovery to a subtree of our doc by including <ce-autoloader> to the respective container factor as an alternative — certainly, we would even have a number of cases for various subtrees.

In fact, we nonetheless need to implement that uncover methodology (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 test our root factor together with each single descendant (*). If it’s a {custom} factor — as indicated by hyphenated tags — however not but upgraded, we’ll try and load the corresponding definition. Querying the DOM that method may be costly, so we must be slightly cautious. We will alleviate load on the principle 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 methodology to dynamically inject a <script> factor:

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("didn't find custom-element definition"));
    });
  });
  el.src = this.elementURL(tag);
  doc.head.appendChild(el);
  return res;
}

elementURL(tag) {
  return `${this.rootDir}/${tag}.js`;
}

Word the hard-coded conference in elementURL. The src attribute’s URL assumes there’s a listing the place all {custom} factor definitions reside (e.g. <my-widget>/parts/my-widget.js). We may give you extra elaborate methods, however that is ok for our functions. Relegating this URL to a separate methodology permits for project-specific subclassing when wanted:

class FancyLoader extends AutoLoader {
  elementURL(tag) {
    // fancy logic
  }
}

Both method, observe 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 not auto-load {custom} components: lacking `root-dir`");
  }
  if(uri.endsWith("https://css-tricks.com/")) { // take away trailing slash
    return uri.substring(0, uri.size - 1);
  }
  return uri;
}

You may be considering 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 wish to account for dynamically added components as effectively. 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 factor seems within the DOM — or reasonably, our respective subtree — which we then use to restart the invention course of. (You may 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 may look into potential race circumstances and examine optimizations. However likelihood is that is ok for many situations. Let me know within the feedback if in case you have a unique method and we are able to evaluate notes!

[ad_2]

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles