You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
The main points are that, using the JavaScript modules plumbing, you can import HTML.
Either in HTML:
<scripttype="module" url="foo.html">
or JavaScript:
import*asfoofrom"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.
Reacted by Matthew Phillips, Abdón Rodríguez, Serhii Kulykov, Kristofer Baxter, Bede Overend, Takayoshi Kochi, Fabian, Tim van der Lippe, Adam Bradley, Peter Burns and 224 more
Reacted by Meghan Denny and Matthew Dean
Reacted by Tim Nguyen
Reacted by Tom Blanchet, Terence Kaite, Hamed, Mario Aleo, JingAn Chen, Jacek Kościesza, Danylo Fedorov, Bruno Gomes, Rhy Moore, Luca Graf and 18 more
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!
Reacted by Abdón Rodríguez, Takayoshi Kochi, Tim van der Lippe, Heriberto Cantú, Mads, Martin Splitt, Clayton Watts, Jason Allen, David Baker, herrernst and 18 more
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?
Reacted by Adam Schwartz, Daniel Herr, Matteo, Yas, Wiktor and Oliver Williams
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:
Pure JS, using either template strings, DOM builder libraries, JSX, etc. (no HTML modules)
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.
Single-file, like Vue and Polymer: JavaScript, HTML and CSS all in one file.
These styles could all be compatible.
Reacted by Domenic Denicola, Abdón Rodríguez, Serhii Kulykov, Kristofer Baxter, Brenton Simpson, Tim van der Lippe, Maxime Le Conte des Floris, Mads, Sean Larkin, Martin Splitt and 27 more
Reacted by Takayoshi Kochi, Jonathan Neal, Yvan da Silva, ExE Boss, Anton Tolkachev, Christoph Obexer, Chris Nguyen, Shane Thacker and Octávio Richter
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.
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:
I want to be able to export JavaScript modules from an HTML module.
I want to be able to query for elements within the HTML module.
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?
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.
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.
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.
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.
Reacted by Jonny Buchanan, Benjamin Strauß, Milosz Frejnik, Linz, Jerzy Krawiec and Thomas Wisniewski
Reacted by Willem Burgers, Christoph Obexer, Bruno Gachie, Miki, krircc, Terence Kaite, matias, John Berg, Markus, gengjiming and 6 more
Reacted by Tim van der Lippe, Martin Splitt, Andres Rios, Rhy Moore, AJ Klein, Athan, Chuck Horton, Peter, John Lim Ding Wei, Nicolas Sauveur and 8 more
@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?
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?
Reacted by Abdón Rodríguez, Tim van der Lippe, Kenji Baheux, Chris at Milieu, Martin Splitt, Andres Rios, Clayton Watts, Randall Leeds, Bruce B. Anderson, Jason Allen and 20 more
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:
...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!
Reacted by Chris at Milieu, Martin Splitt, Jordan Running, James Browning, Clayton Watts, Andrei I., Mario Brandao, Dave Rupert, Jonathan Neal, AJ Klein and 17 more
Reacted by Tomasz Jakut, Kornelia Kobiela, Chris Lorenzo, Tim van der Lippe, Takayoshi Kochi, Abdón Rodríguez, Martin Splitt, Andres Rios, Clayton Watts, Randall Leeds and 14 more
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.)
Reacted by JingAn Chen, Luiz Machado, Kevin Lozandier , Benjamin Strauß, James Bromwell and Oliver Williams
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.
Reacted by Tomek Wytrębowicz, Nicolas Sauveur, Jona Abdinghoff and Kaleidea
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).
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.
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:
importhtmlTemplateThingfrom'foo.html';constdocumentFragment=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><scripttype="module">customElements.define('x-sfwc',classextendsHTMLElement{
#template =import.meta.document.querySelector('template');constructor(){super();this.attachShadow({mode: 'open'}).appendChild(this.#template.content.cloneNode(true));}})</script>
Reacted by Thomas Tränkler, Thomas Steiner, Shane Thacker, Bruce B. Anderson, Johan Lindkvist, Quint Guvernator, Vojtěch Bargl, たふみ / Tafumi, Kito D. Mann, Julian Cataldo and 7 more
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?
Reacted by Richard Flosi, Nicolò Ribaudo, Johannes Ewald, Christian Svensson, Oliver Williams and Gaubee
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.
@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>
`);
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.
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><scriptid="foo-module" type="module">// This is actually available somewhereexportconstfoo=42;</script><scriptid="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
@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'}.
Reacted by Noam Rosenthal, Benny Powers, Jordan Harband, Jens Tschirpig and Oliver Williams
@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.
Activity
justinfagnani commentedon Jun 20, 2017
@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
domenic commentedon Jun 20, 2017
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>.)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.<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?
Hope this helps set the stage!
addyosmani commentedon Jun 20, 2017
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?
justinfagnani commentedon Jun 20, 2017
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:
import template from 'template.html';in the component's module. Maybe eventimport style from 'styles.css';is we include CSS modules.These styles could all be compatible.
domenic commentedon Jun 20, 2017
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.matthewp commentedon Jun 20, 2017
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:
<template>) accessible?TakayoshiKochi commentedon Jun 21, 2017
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
TakayoshiKochi commentedon Jun 21, 2017
Re @matthewp (#645 (comment))
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
TakayoshiKochi commentedon Jun 21, 2017
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.
rniwa commentedon Jun 21, 2017
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.
matthewp commentedon Jun 21, 2017
@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?web-padawan commentedon Jun 21, 2017
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?
AshleyScirra commentedon Jun 21, 2017
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
docthe Document resulting from fetchingmyimport.html. You can then querySelector etc. ondocand 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
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
elemis 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) - maybeimport ".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
Perhaps that could also be reconfigured to re-export a JS module that the HTML module imports, e.g:
...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!domenic commentedon Jun 21, 2017
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.)
justinfagnani commentedon Jun 21, 2017
Depending on future developments of course. Declarative custom elements (which we'll talk about at TPAC) presumably wouldn't need script enabled.
175 remaining items
clshortfuse commentedon Nov 10, 2022
@Swivelgames
You can already create this monstrosity:
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 withclick).Swivelgames commentedon Dec 23, 2022
@Jamesernator Fair enough for private members. However, I still feel that this may still be viable for public fields, no?
clshortfuse commentedon Mar 27, 2023
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
HTMLTemplateElementhas acontentproperty that returns aDocumentFragment. 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 theconstructorphase. That means that if it's never called nothing happens.If it's to consume the JS inside it, maybe a
importedHTML.modulescall 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 withawait 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 toHTMLTemplateElementinstead, so I can stick that in myindex.htmland reference it from my bundledindex.min.jsinstead?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 importwith 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 parsedCSSStyleSheetdone so without interrupting the JS runtime. So it makes sense we should be able to do this with HTML as well.jfbrennan commentedon Jun 23, 2023
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
HTMLTemplateElementwith the samecontentproperty: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:edbaafi commentedon Feb 21, 2025
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:
This is basically what rniwa posted above but using the newly added
withsyntax.I'm already doing this with a rollup plugin at build time and it feels really clean.
Any thoughts?
matthewp commentedon Feb 25, 2025
@edbaafi So scripts don't run I guess?
justinfagnani commentedon Feb 25, 2025
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:
import.meta.url, etc.edbaafi commentedon Feb 25, 2025
@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
@importfrom 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?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:
edbaafi commentedon Feb 26, 2025
@justinfagnani thanks for this.
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).
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
@importwith{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 HTMLto catch up on that partPPS. 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.
justinfagnani commentedon Apr 7, 2025
One feature that we've talked about often wrt HTML modules is the ability to export and import from inline module scripts.
For instance:
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.
justinfagnani commentedon Apr 10, 2025
I filed whatwg/html#11202 for that.
noamr commentedon Apr 9, 2026
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:
<script type=fragment src="...">replaces the script in-place with the contents of the fragment (like a client-side include)I think this covers all the concerns and debates here but there are ~300 comments here so I've likely missed something.
justinfagnani commentedon Apr 9, 2026
@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'}.noamr commentedon Apr 9, 2026
@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.