Skip to content

HTML Modules #645

Open
Open

Description

@justinfagnani

Now that JavaScript modules are on the verge of widespread browser support, we should think about an HTML module system that plays well with it. HTML Imports doesn't have a mechanism for exporting symbols, nor can they be imported by JavaScript, however its loading behavior is quite compatible with JavaScript modules.

@dglazkov sketched out a proposal for HTML modules here: https://github.com/dglazkov/webcomponents/blob/html-modules/proposals/HTML-Imports-and-ES-Modules.md

The main points are that, using the JavaScript modules plumbing, you can import HTML.

Either in HTML:

<script type="module" url="foo.html">

or JavaScript:

import * as foo from "foo.html";

But within the scope of that sketch there are still several questions about the specifics of exporting symbols from HTML and importing to JavaScript.

Activity

  1. justinfagnani commented on Jun 20, 2017

    @justinfagnani
    ContributorAuthor

    @TakayoshiKochi made a polyfill (based on the <script type-module> polyfill by @matthewp) that implements one set of choices to the questions, and shows JS and HTML modules working together: https://github.com/TakayoshiKochi/script-type-module/tree/html-module-experiment

  2. domenic commented on Jun 20, 2017

    @domenic
    Collaborator

    Thanks for starting the discussion, @justinfagnani!

    For context for others, I've been involved with @TakayoshiKochi and others trying to firm up what HTML modules means before we present it widely. There's still a variety of possibilities. Here's my high-level overview:


    Writing a custom element that authors can include using a single file is a bit tricky. In particular, how do you get your template HTML? (Which is often literally a <template>.)

    • If you want to stay self-contained, and thus friendly to consumers, you're currently forced to inline your HTML into your JavaScript as a template string, then later use innerHTML. This is costly; it requires first parsing it in JavaScript, then later as HTML, and using up extra memory for both representations. It requires all-at-once parsing, instead of streaming, and requires it to be done on the main thread (I think). And it defeats the preload scanner for any subresources.
    • If you want to "use the platform", you'll have to ask your consumers to include the <template> in their index.html, with some well-known ID. Then all of the above disadvantages disappear, but consuming your library is very un-ergonomic.

    At a high level, HTML modules wants to solve this problem. I think the case for it being a worthwhile problem would be stronger if we had data on the costs of the HTML-in-a-JS-string solution, but just by inspection it seems pretty bad. Still, I hope we can provide some data.


    The next big question then is about developer ergonomics: what should the authoring and consumption experience for web components be?

    • At one extreme, we could just allow importing of inert DocumentFragments via the JS module system. This solves the above problem in a minimal, simple fashion. But, it means you cannot collocate your HTML and JS into a single file. Most modern frameworks seem to aim for a developer experience of collation, from React's JSX, to Vue's .vue files, to Polymer's HTML imports usage, to Angular's HTML-in-a-JS-string approach.
    • At another, we could work to add some opinionated semantics to imported HTML files that make them good as a "container" format for a web component. This is the approach @TakayoshiKochi has gone with, and I think it's a good illustration. It's much less of a primitive, and requires adding new unusual semantics (e.g. executing scripts outside the main document), but that might be OK.

    Hope this helps set the stage!

  3. addyosmani commented on Jun 20, 2017

    @addyosmani

    Thanks for getting a public discussion going, @justinfagnani!

    I see HTML Modules as being a good container format for achieving generic subresource dependency specification. They solve a need for platform-level colocated <template>, <style> and <script>/Module in a similar style to what I would get with something like Vue's .vue files or Polymer's existing HTML Imports. I'd love for them to sufficiently export a JS module - I found this to be a shortcoming of HTML Imports when I last used them.

    Some questions:

    • What it is about HTML Modules that makes them specific to Web Components? If a third-party decides to just use HTML + CSS + JS in this container format, that should just work too right? I think we should cater for a few different styles of component to work well with HTML Modules.

    • Are HTML Modules primarily a DX convenience for containment? or do we also foresee trying to bake in a performance carrot (e.g preload scanner benefits) to the design?

    • How do we see HTML Modules fitting with respect to the broader Web Packaging efforts?

  4. justinfagnani commented on Jun 20, 2017

    @justinfagnani
    ContributorAuthor

    I also want to point out that HTML modules would not prescribe how component developers package their libraries, or even prescribe Web Components for that matter.

    There are a number of styles that components could be written and/or packaged:

    1. Pure JS, using either template strings, DOM builder libraries, JSX, etc. (no HTML modules)
    2. Logic in JS, template/CSS in HTML: import template from 'template.html'; in the component's module. Maybe event import style from 'styles.css'; is we include CSS modules.
    3. Single-file, like Vue and Polymer: JavaScript, HTML and CSS all in one file.

    These styles could all be compatible.

  5. domenic commented on Jun 20, 2017

    @domenic
    Collaborator

    These styles could all be compatible.

    That's a good point. Even if we go with an opinionated container format with new capabilities, like @TakayoshiKochi's prototype, it will likely be possible to opt-out of those new capabilities, e.g. by just making your main element a <template> so that everything inside it is inert.

  6. matthewp commented on Jun 20, 2017

    @matthewp

    It looks like @TakayoshiKochi's experiment doesn't create a new document for the imported module. Not sure if this is an intentional omission or not, as the @dglazkov sketch does mention there being a new document like in html imports. Here's an example module for those interested.

    In the interest of listing problems and not solutions I would say some things I want (in addition to other things mentioned by people above) are:

    1. I want to be able to export JavaScript modules from an HTML module.
    2. I want to be able to query for elements within the HTML module.
    3. I want to be able to "reach in" to an HTML module some how from the outside and use stuff other than the HTML modules within. But maybe if (1) and (2) are satisfied that would mean that an HTML module could make the other parts (like the <template>) accessible?
  7. TakayoshiKochi commented on Jun 21, 2017

    @TakayoshiKochi
    Member

    Thanks @justinfagnani for starting this thread! Thanks @domenic for the summary.
    I was wondering if this is a good place as @addyosmani mentioned if HTML Modules may not be
    specifically for web components. But as it is, this is good starting here in public:)

    We're open to any questions / problems for HTML modules.
    Feel free to pour your thoughts here.

    FYI, here's slide deck I presented in BlinkOn back in February:
    https://docs.google.com/presentation/d/1ksnC9Qr3c8RwbDyo1G8ZZSVOEfXpnfQsTHhR5ny9Wk4/edit

  8. TakayoshiKochi commented on Jun 21, 2017

    @TakayoshiKochi
    Member

    Re @matthewp (#645 (comment))

    It looks like @TakayoshiKochi's experiment doesn't create a new document for the imported module.

    Yes, it was intentional. Imported HTML is treated as DocumentFragment (as opposed to Document), so we don't have to bother about various semantics to be satisfied, although it yields some weirdness (e.g. why/how can <script> inside be executed?). I'm interested if you prefer Document (other than that was described in Dimitri's doc) to DocumentFragment.

    If you're interested in history, here's record of Document vs DocumentFramgent for HTML Imports:
    https://www.w3.org/Bugs/Public/show_bug.cgi?id=22305

  9. TakayoshiKochi commented on Jun 21, 2017

    @TakayoshiKochi
    Member

    We are interested in hearing requirements from framework authors, as HTML modules is not (should not be?) specific to web components definition (= container for custom elements and shadow DOM definition).

    I admit that my experimental polyfill was biased towards HTML Imports + web components, and would be a good fit for Polymer or Vue use cases, but I would be more excited if the resulting HTML modules would be usable for more than these frameworks or libraries.

    In my blink-dev thread, a developer from Scirra introduced me his very inspiring blog post:
    https://www.scirra.com/blog/ashley/34/html-imports-are-the-best-web-component
    The post is long, but I recommend reading it from top to bottom - my interpretation is that HTML Imports fit their product development requirement quite well, even though they do not use Shadow DOM and do use only little Custom Elements. That exemplifies the need for something that supports scalable development on web platform, and HTML Imports is one key primitive for it.

  10. rniwa commented on Jun 21, 2017

    @rniwa
    Collaborator

    Here's my take on this. In today's world, developers are putting HTML inside their JS, not JS inside their HTML. The fact that we don't currently preload resources in a string literal, or we end up two string representations of HTML if you used string literal to include HTML in a JS file is a pure implementation detail. There is nothing preventing us from implementing an optimization if there was a well known symbol which was used to tag a HTML in a JS.

    Furthermore, for various performance reasons, we really need to have a mechanism to define an in-file ES6 module; a mechanism which allows multiple modules to be defined within a single JS file. Once we have that, then it's very natural to define three modules: one with HTML, one with CSS, and one with JS in a single JS file.

    So I'm not all convinced that we need to put JS into HTML as done in the HTML import. In fact, we'd likely oppose to such an approach on the basis that popular JS frameworks such as React have gone to the completely other direction of embedding HTML inside JS.

  11. matthewp commented on Jun 21, 2017

    @matthewp

    @rniwa I find this opinion confusing given your interest in template parts. Are you not interested in that feature either, now? Or are you saying you'd prefer to define your <template> (with parts) as a string literal in JS rather than in HTML. Why?

  12. web-padawan commented on Jun 21, 2017

    @web-padawan

    the basis that popular JS frameworks such as React have gone to the completely other direction of embedding HTML inside JS.

    While not being a framework author nor a browser developer here, just an end-user, I'd like to say that, although it is a widely adopted approach, it still requires tooling and you'll not be able to serve vanilla HTML, CSS and JS unprocessed by stuff like Webpack and so on.

    I'd also like to remind you that React was initially built with PHP where including HTML was once widely used. But is such a mixing really considered as a good practice by PHP developers now?

    Furthermore, how shall HTML modules work in browsers with disabled JavaScript? If markup stays in HTML, I can imagine them still working somehow. But what if it is placed in string literals?

  13. AshleyScirra commented on Jun 21, 2017

    @AshleyScirra

    I wrote this blog post. I'm interested in participating in work for HTML modules, and I think our experience is valuable: we have published a commercial PWA using ~300 HTML imports.

    As I touched on in the blog, I quite like the idea of being able to import a HTML file and get a Document, much like XHR for type "document". So this:

    import * as doc from "./myimport.html"

    would be similar to assigning doc the Document resulting from fetching myimport.html. You can then querySelector etc. on doc and use its DOM content in the JS module. (IMHO, this is far better than pasting chunks of markup in to strings in JS)

    Then all you need to do is add a HTML tag that can propagate to further dependencies. I suggested changing

    <link rel="import" href="import.html">

    to be equivalent to

    <script type="module">
    import * as doc from "./myimport.html"
    </script>
    

    It could equally be <script type="module" src="myimport.html"></script> to do the same. This means further scripts/imports/modules are loaded and run, etc.

    I have to say style application from imports is a useful feature for us - see my example of a dialog definition for an example. It's possible a framework could work around this (e.g. applyStylesFrom(doc)), but it seems a shame if the dialog definition example can't work natively.

    If HTML modules covered that, I'd guess that largely covers everything we use imports for. In our case they're largely just the architectural scaffolding that brings together all the components of our web app, and as I tried to emphasise in my blog, they excel at that, particularly since it covers all three aspects of a web app (markup, style, script, at least until Google roll back style application 😢).

    I am strongly against trying to use script for any markup or style content. I know some frameworks are having success with that approach, and so we shouldn't do anything that makes that harder. But if you have 1000 lines of markup, surely nobody wants to paste that in to a script as a giant string? I strongly believe that there should at least be the provision for leaving markup in HTML files, and not orient the spec around doing what one framework does today. Remember frameworks come and go over the years. In our case, our PWA is notable for not using VDOM, has almost no use of markup-in-script, uses plain markup (no Angular-style directives), no templating (like {{this}} in markup), and no two-way data binding. I don't think any other framework on the web today takes this approach, but I believe our PWA proves that you can still build scalable, complex web apps that way. I do worry that people have framework-blindness where they think things should be done like the frameworks do, rather than thinking in terms of providing general-purpose capabilities that frameworks of different designs and approaches can make use of, even in the future when everything likely changes.

    Anyway, here's a couple of extra ideas that may be useful to extend the utility of HTML modules as I described them. Perhaps it'd be useful to add a selector to pick out specific elements, e.g.:

    import "#elem" as elem from "./myimport.html"

    Now elem is the DOM element returned by matching the selector #elem on myimport.html. Not sure how to handle multiple results (e.g. using ".myclass" as a selector) - maybe import ".myclass" as [resultsArray] from ".myimport.html"?

    Finally I don't know if it makes sense to export from a HTML module, but perhaps you could have something like:

    import myElem from "./myimport.html"

    where myimport.html has a special tag like

    <export name="myElem">
        <div>This div is an exported element!</div>
    </export>
    

    Perhaps that could also be reconfigured to re-export a JS module that the HTML module imports, e.g:

    <export name="submodule">
        <script type="module" src="a.js"></script>
    </export>
    

    ...then allowing import submodule from "./myimport.html", which propagates the exports from a.js through the HTML import and in to another JS module. I feel like I'm shooting in the dark there though!

  14. domenic commented on Jun 21, 2017

    @domenic
    Collaborator

    Furthermore, how shall HTML modules work in browsers with disabled JavaScript? If markup stays in HTML, I can imagine them still working somehow. But what if it is placed in string literals?

    I can answer that, at least: they won't. HTML modules are part of the module system, which is entirely dependent on JavaScript.

    Even HTML imports never worked in browsers without JavaScript. (The document would be "imported", but useless, since you need script to access imported documents.)

  15. justinfagnani commented on Jun 21, 2017

    @justinfagnani
    ContributorAuthor

    Even HTML imports never worked in browsers without JavaScript. (The document would be "imported", but useless, since you need script to access imported documents.)

    Depending on future developments of course. Declarative custom elements (which we'll talk about at TPAC) presumably wouldn't need script enabled.

  16. 175 remaining items

  17. clshortfuse commented on Nov 10, 2022

    @clshortfuse

    @Swivelgames

    You can already create this monstrosity:

    <template id="myCustomElementTemplate">
        <button onclick="this.getRootNode().host.constructor.handleClick.call(this, event)">Click me!</button>
    </template>

    And yes, it works and is cloneable. Though on* has the browser construct a new function and bind it with a EventListener that cannot be removed from JS. That doesn't scale well for very large DOMs (eg: table grid cells with click).

  18. Swivelgames commented on Dec 23, 2022

    @Swivelgames

    @Jamesernator Fair enough for private members. However, I still feel that this may still be viable for public fields, no?

  19. clshortfuse commented on Mar 27, 2023

    @clshortfuse

    I've kinda moved to just wanting HTML to parse HTML and then some extra code for the client to consider how to use it. It then moves to the current, live document which decides when and how to adopt the imported HTML to the current, live document.

    For example, if an HTML import has a <link> URL. Should it always start fetching that link? If it has imports of other JS scripts, does it happen before it lands on the JS. What about a synchronous, ES5 script? Does it need to run to completion before it's handed back? Could a <script> change its own document and add another <script>. Can it dynamically build a <link>?

    It kinda leans to an HTML import should probably be a DocumentFragment + extras. This would be similar to how HTMLTemplateElement has a content property that returns a DocumentFragment. Those extras could be invocation functions/properties that depend on the intended purpose JS side. If it's to be used as a Web Component, maybe it'll be cloned during the constructor phase. That means that if it's never called nothing happens.

    If it's to consume the JS inside it, maybe a importedHTML.modules call which can be synchronous for those that want it as a critical for runtime: import { modules } from 'file.html'. Or you can do it asynchronously with await import.

    If it's a set of resources, we might want to immediate start fetching those resourced by calling document.adoptNode.

    What really gets interested is, should we just lock all the new intended functionality behind an import? For example CSS imports are just constructed CSSStyleSheet. What if, in the interest of minification, I want to bundle that functionality into one file, either in JS, or part of the main HTML file. Do I need to tell the browser to import an HTML file to get the import scoping? That means a call back to the server to return a resource, which is wasted time. Couldn't this functionality be added to HTMLTemplateElement instead, so I can stick that in my index.html and reference it from my bundled index.min.js instead?

    Right now, I'm experimenting the use case of splitting a page that has something like 30 different Web Components as critical and non-critical Web Components. As of now, HTML-in-JS requires parsing of the string and that's done synchronously. That means my Web Components are loaded in series. I would like them be loaded in parallel by using await import with an HTML Module. It'll reduce the deployment size since we don't need to bundle non-crtitical HTML as strings. We can already do this with CSS, as the browser will return a parsed CSSStyleSheet done so without interrupting the JS runtime. So it makes sense we should be able to do this with HTML as well.

  20. jfbrennan commented on Jun 23, 2023

    @jfbrennan

    Just throwing in my support and desire for HTML Modules.

    I like that idea of using them to import what looks to be similar to an HTMLTemplateElement with the same content property:

    import htmlTemplateThing from 'foo.html';
    
    const documentFragment = htmlTemplateThing.content.cloneNode(true);
    
    // Do stuff with documentFragment or append it wherever you want...

    The alternative today is authoring HTML as JS template literals and being limited to innerHTML.

    More than that though, we so badly need this for packaging Web Components.

    Authoring and "importing" a complete Web Component is a pretty lame experience. You have to somehow get all your components' template source code, e.g. <template>My Web Component<style>:host {...}</style></template>, into the main document and then include the JS with the Custom Element definitions. Or you use template literals or imperative DOM to construct the template in JS. It's janky and error-prone and inefficient either way. I look at (and use) Riot.js and Vue.js single-file components with envy. I've been experimenting with a Single File Web Components hack out of desperation. Would love for the web platform to make importing this HTML file possible:

    <template>
      Single File Web Component!
      <style>
        :host {...}
      </style>
    </template>
    <script type="module">
      customElements.define('x-sfwc', class extends HTMLElement {
        #template = import.meta.document.querySelector('template');
    
        constructor() {
          super();
          this.attachShadow({ mode: 'open' }).appendChild(this.#template.content.cloneNode(true));
        }
      })  
    </script>
  21. edbaafi commented on Feb 21, 2025

    @edbaafi

    Hello justinfagnani and all! I'm not sure if this is the right place to post this, but now that the import attributes proposal has reached stage 4, and all major browsers besides Firefox are already supporting import json from './some.json' with {type: 'json'} (and Chrome supports {type: 'css'}) perhaps it's time to revisit the JavaScript side of the HTML import question.

    Consider the following:

    import styleSheet from './custom-element.css' with {type: 'css'};
    import template from './custom-element.html' with {type: 'html'};
    
    export class CustomElement extends HTMLElement {
    
        #shadowRoot;
    
        constructor() {
            super();
            this.#shadowRoot = this.attachShadow({ mode: 'closed' });
            this.#shadowRoot.adoptedStyleSheets = [styleSheet];
            this.#shadowRoot.appendChild(template.content.cloneNode(true));
        }
    }
    

    This is basically what rniwa posted above but using the newly added with syntax.

    I'm already doing this with a rollup plugin at build time and it feels really clean.

    Any thoughts?

  22. matthewp commented on Feb 25, 2025

    @matthewp

    @edbaafi So scripts don't run I guess?

  23. justinfagnani commented on Feb 25, 2025

    @justinfagnani
    ContributorAuthor

    Scripts are indeed the toughest question, IMO, because they have to be addressed in any attempt at this feature, MVP or no.

    If scripts don't run in the first cut, they can't suddenly run in a future update. If they run in the first cut, we have to get the semantics correct in a forward-compatible way, including whether or not exports from inline scripts become exports in the HTML module and a few other things.

    I would love to see some incremental way to start... I think there are two potential approaches that could be done in parallel:

    • A minimal HTM modules where the presence of scripts throw in module evaluation. This preserves the ability to move forward with running scripts in the future. We can focus on exporting DOM.
    • Adding some features we've talking about under HTMl modules to main-page HTML itself where scripts already do run. Things like importing and exporting between inline scripts. Getting a promise of the exports object from a script tag. import.meta.url, etc.
  24. edbaafi commented on Feb 25, 2025

    @edbaafi

    @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>
    `);
    
    Image
  25. edbaafi commented on Feb 26, 2025

    @edbaafi

    @justinfagnani thanks for this.

    Scripts are indeed the toughest question, IMO, because they have to be addressed in any attempt at this feature, MVP or no.

    If scripts don't run in the first cut, they can't suddenly run in a future update. If they run in the first cut, we have to get the semantics correct in a forward-compatible way, including whether or not exports from inline scripts become exports in the HTML module and a few other things.

    I think if this starts as an MVP without deciding on the script question then this question is very similar to the @importquestion for the CSS side of import attributes. They ended up warning not throwing IIRC and this post stuck out: #870 (comment)

    Particularly the part about if we throw now but start supporting this later what does that mean? I think for imports with {type: 'html'}, it means we couldn't polyfill (at runtime I mean) the potentially new behavior (i.e. eventually allowing scripts) for browsers that decided to throw now. It would take some monkey patching but if the template is allowed to be imported with a disabled script, we could probably patch cloneNode to detect an instance of HTMLTemplateElement's content property and to find any scripts and re-add them to cause them to load similar to how I showed above (for the case where scripts added with innerHTML don't load).

    The feasibility of such a patch might depend on the semantics, but at least there is a possible way forward. What do we lose by not throwing? A developer who makes a mistake today (doing something the spec and a warning can tell them not to do) causes their code to work differently at some later point. I think this is acceptable because they can fix that issue, but we can't take back browsers that ship with behavior that blocks a way forward (Safari especially).

    I would love to see some incremental way to start

    Agree even if I see the danger in throwing, not, in not throwing. I think a major use case is enabled by just allowing this syntax for loading html templates without dealing with the script question. At least at first glance I think warning not throwing like was done for @import with {type: 'css'} leaves us with the most flexibility. The warning is that you have a script that is currently not loading but could in the future so leave it there at your own risk.

    Thoughts?

    PS. I'll have to read more about what's been discussed re: HTML modules to main-page HTML to catch up on that part

    PPS. My argument for warning not throwing and that this leaves a potential way to pollyfill future behavior is dependent on the script tag not being removed but just not loading in the interim.

  26. justinfagnani commented on Apr 7, 2025

    @justinfagnani
    ContributorAuthor

    One feature that we've talked about often wrt HTML modules is the ability to export and import from inline module scripts.

    For instance:

    <html>
      <script id="foo-module" type="module">
        // This is actually available somewhere
        export const foo = 42;
      </script>
      <script id="bar-module" type="module">
        import {foo} from '#foo-module'; // strawman specifier syntax
      </script>
    </html>

    This feature seems pretty separable from HTML modules and something that could be useful in the main page, especially for declarative notebook-style documents (projects like Observable have to completely side-step imports to be able to reference things between script tags). It's also related to whatwg/html#7367

    I searched for a standalone issue for this and didn't find one yet, so I'll open one in https://github.com/whatwg/html soon.

  27. justinfagnani commented on Apr 10, 2025

    @justinfagnani
    ContributorAuthor

    I filed whatwg/html#11202 for that.

  28. noamr commented on Apr 9, 2026

    @noamr

    I am looking into whether this (together with client-side includes) can be part of the next work on declarative partial updates.
    Please see https://github.com/WICG/declarative-partial-updates/blob/main/fragment-include-explainer.md for details.
    In short:

    • fragment modules, in the spirit of this proposal
    • A fragment is cloned when imported
    • <script type=fragment src="..."> replaces the script in-place with the contents of the fragment (like a client-side include)
    • imported fragments are safely sanitized by default, and can be made unsafe (with a run-scripts option) by an opt-in (attribute or some such)
    • async/defer work like in other scripts
    • relative URLs are not rebased to the URL of the import. This can be a future enhancement but is a big undertaking.

    I think this covers all the concerns and debates here but there are ~300 comments here so I've likely missed something.

  29. justinfagnani commented on Apr 9, 2026

    @justinfagnani
    ContributorAuthor

    @noamr I think that proposal may be conflating HTML Modules (and HTML Imports before them) a bit with HTML Includes, which is a problem we've had for a while.

    Specifically, HTML Modules should act like a lot like JS, JSON, and CSS modules - they serve as containers for definitions and values, and their exports are shared among their importers. Their exports should not be cloned when imported.

    The first problem is that breaks the usual semantics of imports/export and modules. Exports are live, and just importing does not trigger any actions at all. A module cannot even tell that an export was imported somewhere. I think some side-effect upon import would be a very big departure for JS.

    Secondly, if multiple modules import a template from an HTML module, they must get the same template instance. If you clone the template on import you can break template systems that rely on template identity for DOM stable updates.

    The next issue I see is sanitization. Everything from an HTML module should be as trusted as developer-controlled script in JS modules. Like JS, CSS, and JSON, you should not import untrusted resources. HTML Modules need to be able to run script, after all. Sanitization directly interferes with the primary use case of HTML Modules, which is to allow developer to put HTML in HTML files, rather than strings in JS files.

    So, {type: 'fragment'}* might be it's useful own thing, but it's quite separate from HTML Modules as far as I can tell, and I think given the long history of confusion between the two concepts, that distinction should be clarified.

    I'm also not sure about the use case for importing fragments directly into JS. The use case seems much more obvious in HTML, where HTML Includes are loudly requested, but from JS? I don't see that as much. If we had HTML modules, a developer could easily import and clone a template themselves. If the content is untrusted, I'm not sure they should be using the module system.

    *fragment of what? I don't think that's obvious in a JS context. It should probably be {type: 'html-fragment'}.

  30. noamr commented on Apr 9, 2026

    @noamr

    @justinfagnani I think that the "fragment inlcude" proposal is somewhere in the middle between imports and includes. But indeed it doesn't adress some of the issues here of having the HTML modules be shared/alive, so I'll keep it as separate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions