Re: [WICG/webcomponents] HTML Modules (#645)

edbaafi left a comment (WICG/webcomponents#645)

@matthewp Are you talking about in the rollup plugin? Yeah I hadn't thought about it as I don't need that for my use case (I am bundling StyleSheets included using `@import` from the CSS imports though which is currently out of spec IIRC).  But I guess what you're referring to is that scripts added to templates with innerHTML will not load and were wondering if we could get around that with build tools?

```
const html = document.createElement('template');
html.innerHTML = `
  <script>
      alert('Without a patch, scripts cannot loaded from templates set with innerHTML');
  </script>
  <span>Shadow Content</span>
`;


class TestTemplateScripts extends HTMLElement {
    #shadowRoot;
    constructor() {
        super();
        this.#shadowRoot = this.attachShadow({ mode: 'closed' });
        this.#shadowRoot.appendChild(html.content.cloneNode(true));
    }
}

customElements.define('test-template-scripts', TestTemplateScripts);

```

In any case this limitation can be overcome with the following (all the semantics questions aside) so we could do this in the bundler and export a template where scripts do work:

```
const createTemplate = (innerHTML) => {
    const template = document.createElement('template');
    template.innerHTML = innerHTML;
    const scripts = template.content.querySelectorAll('script');

    for (const script of scripts) {
        // Scripts created with cloneNode() won't load, so create the script
        // element and then copy the text content and attributes manually
        const newScript = document.createElement('script');
        for (const attributeName of script.getAttributeNames()) {
            newScript.setAttribute(attributeName, script.getAttribute(attributeName));
        }
        newScript.textContent = script.textContent;

        // Avoid replaceWith for legacy engine support
        script.parentNode.insertBefore(newScript, script);
        script.parentNode.removeChild(script);
    }
    return template;
}

const html = createTemplate(`
  <script>
      alert('With this patch, scripts can now be loaded from templates set with innerHTML');
  </script>
  <span>Shadow Content</span>
`);
```

<img width="1083" alt="Image" src="https://github.com/user-attachments/assets/d38fde44-9ca3-4cdc-881b-01fb6482e12e" />

-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/645#issuecomment-2683511090
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/645/2683511090@github.com>

Received on Tuesday, 25 February 2025 23:22:04 UTC