3 ms·
Technically you could also just write a bit of JS within the HTML to do without needing any of the first 3. You could querySelectorAll and check the src attrib
by mewpmewp2 3y ago
Technically you could also just write a bit of JS within the HTML to do without needing any of the first 3.
You could querySelectorAll and check the src attribute etc, then fetch the content put it in the innerHTML.
<remote-fragment src="https://..." />
<script>
document.querySelectorAll("remote-fragment").forEach(async (el) => {
const src = el.getAttribute("src");
const result = await fetch(src).then((res) => res.text());
el.innerHTML = result;
});
</script>
Or if you want to react to any such component inserted at times down the line or src attribute changes, you could use MutationObserver.
- lelanthran 3y agoThat breaks on edge cases. For example it won't work recursively when a fetched fragment has fragments of its own. Or when the js snippet loads before some fragment element is loaded (say, from a DOM update). The nice thing about custom elements is that you get to treat them exactly like normal elements.
- mewpmewp2 3y agoIn this case you could use MutationObserver - although we are doing manually the logic web components provide, but my point is that you can do it also without using web components. My code doesn't include attribute changes, but this should be possible to also do with MutationObserver. <body> <script> const onRemoteFragmentMount = async (el) => { const src = el.getAttribute("src"); const result = await fetch(src).then((res) => res.text()); el.innerHTML = result; }; const callback = (mutationsList, observer) => { for (let mutation of mutationsList) { if (mutation.type === "childList") { mutation.addedNodes.forEach((node) => { if (node.tagName === "REMOTE-FRAGMENT") { onRemoteFragmentMount(node); } }); } } }; const observer = new MutationObserver(callback); const bodyElement = document.querySelector("body"); observer.observe(bodyElement, { childList: true, subtree: true, }); </script> <remote-fragment src="..." /> </body>
- KatrinaKitten 3y agoWhile you certainly could do this, a major benefit of web components is that you get all of this for free out of the box. It's less error/mistake prone, keeps your code cleaner and more obvious exactly what it does, etc.