jj
    Preparing search index...

    Function fetchTemplate

    • Fetches an HTML template and returns it as a wrapped DocumentFragment.

      Parameters

      • url: string | URL

        The HTML file location.

      Returns Promise<JJDF<DocumentFragment>>

      A JJDF wrapping a DocumentFragment parsed from the fetched HTML.

      Because this function returns a detached fragment, you can load templates:

      • eagerly (initialize the promise, reuse the result many times)
      • lazily (fetch only when a component connects)

      The returned JJDF is suitable for both Shadow DOM and Light DOM flows.

      // Eager loading: fetch once at module scope, then reuse
      const templatePromise = fetchTemplate(import.meta.resolve('./my-card.html'))

      class MyCard extends HTMLElement {
      #root

      async connectedCallback() {
      this.#root = JJHE.from(this).setShadow('open').shadow
      this.#root.addTemplate(await templatePromise)
      }
      }
      // Lazy loading: initialize once on first connection
      class MyLazyCard extends HTMLElement {
      static #templatePromise
      #root

      async connectedCallback() {
      this.#root = JJHE.from(this).setShadow('open').shadow

      if (!MyLazyCard.#templatePromise) {
      MyLazyCard.#templatePromise = fetchTemplate(import.meta.resolve('./my-lazy-card.html'))
      }

      this.#root.addTemplate(await MyLazyCard.#templatePromise)
      }
      }

      If the fetch fails or the response is not ok or the retrieved content cannot be parsed as HTML.