Today, I wanted to talk about the "right" way to load web components to ensure they work predictably every time. Let's dig in! The challengeWeb components are self instantiating. Let's imagine you're creating a table of contents. When you use a traditional JavaScript library, you explicitly instantiate the library on a specific element.
But with web components, all you need to do is include the custom element associated with the component.
The JavaScript automatically runs on that element once it…
… whichever happens last. This can create problemsIf you load your JavaScript in the footer, or use But if you load the script for a web component in the Consider the What happens if you load your The second the browser hits that If you put your The script breaks. The simple fixThe obvious fix is load your JS in the footer, But as my friend Alex Riviere pointed out, people can't always control when and how scripts load. Maybe it's included as a third-party script. Maybe their CMS always loads code in the Whatever the reason, if you're building something that's going to be used in unpredictable ways, you owe it to the end user to make it as stable and resilient as possible. The web is a weird and unpredictable place, and beginners and non-technical folks deserve good software just as much as seasoned devs do! Bulletproofing web component loadingThe trick, then, is to wait for the DOM to be ready. Remember that from the jQuery era? It's back, y'all! I'm using a pattern in Kelp to make this predictable across all of my web components. Every component has an Inside the
I'm grateful to Patrick Nelson for catching this issue in Kelp and rubber ducking the best path forward with me. Patrick also made a few improvements to the Kelp testing process. You can learn more about Kelp over at KelpUI.com. Like this? A Go Make Things membership is the best way to support my work and help me create more free content. Cheers, Want to share this with others or read it later? View it in a browser. |
0 Komentar untuk "[Go Make Things] Bulletproof web component loading"