
An Approach to Lazy Loading Custom Elements
Chances are you won’t actually need all this; there’s usually a simpler approach. Used deliberately, the techniques shown here might still be a useful addition to your toolset.
For consistency, we want our auto-loader to be a custom element as well — which also means we can easily configure it via HTML. But first, let’s identify those unresolved custom elements, step by step:
Of course, we still have to implement that discover
method (as part of the AutoLoader
class above):
Here we check our root element along with every single descendant (*
). If it’s a custom element — as indicated by hyphenated tags — but not yet upgraded, we’ll attempt to load the corresponding definition. Querying the DOM that way might be expensive, so we should be a little careful. We can alleviate load on the main thread by deferring this work:
Now we can move on to implementing the missing load
method to dynamically inject a <script>
element:
Note the hard-coded convention in elementURL
. The src
attribute’s URL assumes there’s a directory where all custom element definitions reside (e.g. <my-widget>
→ /components/my-widget.js
). We could come up with more elaborate strategies, but this is good enough for our purposes. Relegating this URL to a separate method allows for project-specific subclassing when needed:
Either way, note that we’re relying on this.rootDir
. This is where the aforementioned configurability comes in. Let’s add a corresponding getter:
You might be thinking of observedAttributes
now, but that doesn’t really make things easier. Plus updating root-dir
at runtime seems like something we’re never going to need.
Now we can — and must — configure our elements directory: <ce-autoloader root-dir="/components">
.
This way, the browser notifies us whenever a new element appears in the DOM — or rather, our respective subtree — which we then use to restart the discovery process. (You might argue we’re re-inventing custom elements here, and you’d be kind of correct.)
Our auto-loader is now fully functional. Future enhancements might look into potential race conditions and investigate optimizations. But chances are this is good enough for most scenarios. Let me know in the comments if you have a different approach and we can compare notes!
If you need help creating a digital marketing strategy for your business, don’t hesitate to contact one of Digidude’s consultants.
Post a Comment
You must be logged in to post a comment.