How to lazy load this custom HTML Component?

Ive lots of playground elements in the html, but for each is loading the whole library and all at once which is has a huge impact on the loading of the page.
https://drive.google.com/file/d/1K-TYa3n5H18BVYHnfWv96lEK_k8Q6rJc/view?usp=sharing

Link of the library: https://github.com/google/playground-elements

I’m using this in the head:

<script defer type="module">
 import playgroundElements from 'https://cdn.jsdelivr.net/npm/playground-elements@0.18.1/+esm'
</script>

and this for each code example:

<playground-ide defer resizable line-wrapping>
  <script type="sample/html" filename="index.html">
  <!doctype html>
  <html>
    <head>
      <link rel="stylesheet" href="mi-hoja-de-estilos.css">
    </head>
    <body>
      <p>just an example</p>
  
    </body>
  </html>
  </script>

  <script type="sample/css" filename="mi-hoja-de-estilos.css">
/* code css*/
  </script>
</playground-ide>

The following code at least starts loading only after one instance of the html component comes into view with an intersection observer, but it loads all the instances instead of only the visible one/ones.

only the visible one.
<script defer type="module">

  // Set up our observer:
  let observerPlayground = new IntersectionObserver((entries, observerRef) => {
    entries.forEach(async (entry) => {
      // `isIntersecting` will be `true` if any part of the element is currently visible
      if (entry.isIntersecting) {
        // We are assuming here that your Web Component is located in a file
        // named after its tag name
        const name = entry.target.nodeName.toLowerCase();

        // Once we've observed this element come into view, we can safely remove
        // the observer since we won't need to import the WC code again
        observerRef.unobserve(entry.target);

        try {
          // Let's load the WC code
          const playgroundElementsModule = await import('https://cdn.jsdelivr.net/npm/playground-elements@0.18.1/+esm');
          // Use the imported module as needed
          console.log(playgroundElementsModule);
        } catch (error) {
          console.error('Error loading playground-elements:', error);
        } finally {
          // Disconnect the observer to stop observing the current element
          observerRef.disconnect();
        }
      }
    });
  });

  // Observe all components with the desired class
  const els = document.querySelectorAll('playground-ide');
  els.forEach((el) => {
    observerPlayground.observe(el);
  });
</script>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.