Repository navigation
Description
(Credit to @dvoytenko for this proposal.)
Problem statement
It's a common pattern to serve most of your JavaScript from CDNs, but use an inline script for configuration settings. E.g.
<script>
self.configuration = {
deviceType: "tier1"
/* ... */
};
</script>
<script src="https://cdn.example.net/script.js">where https://cdn.example.net/script.js could end up using self.configuration.
This setup is fragile, as it relies on the web page author to ensure the inline script appears before any CDN-included scripts, and and doesn't play well with async="" which might cause scripts to execute early.
Additionally, some authors would prefer to use modules for this, so that the dependency between script.js and the global configuration is explicit.
Proposal
We could add an exports property to HTMLScriptElement. This was mentioned previously in #2235, but without use cases. Then we could have this setup:
<!-- Order no longer matters; async="" is fine -->
<script type="module" async src="https://cdn.example.net/script.mjs">
<script type="module" async id="configuration">
export const deviceType = "tier1";
// ...
</script>Where script.mjs contains
const { deviceType } = await (await waitForElement("#configuration")).exports;and waitForElement is a developer-written helper utility that uses a MutationObserver to wait for the specified element to appear.
Note that exports itself would be a promise, because in the general case the inline module might itself use top-level await. That's not what's going on in our configuration-based example, so in our case the promise will immediately fulfill, but it seems like the right primitive at the spec level.
There could also be a level of indirection, so that script.mjs doesn't need its own waitForElement function. For example if script.mjs did
import { deviceType } from "./configuration.mjs";where https://cdn.example.net/constants.mjs contains some default configuration values, then the page itself could use an import map to remap https://cdn.example.com/configuration.mjs to its own script that looks like the following:
const { deviceType } = await (await waitForElement("#configuration")).exports;
export deviceType;Alternative considered
Another way of accomplishing this, which is less powerful but potentially easier to use, would be to introduce the ability to directly import an inline script. Something like the following:
import { deviceType } from "document:configuration";The problem with this idea is that the semantics of resolving document:configuration specifiers is tricky:
-
The most natural thing would be that resolving does a synchronous lookup in the current state of the document, and fails if there is no element with the specified ID. However, then you basically go back to the current state of things, just with modules: you'll still have problems if your inline module isn't before any CDN-provided modules, or if you use
async="". You could combine it withwaitForElement("#configuration")+ dynamicimport()like so:await waitForElement("#configuration"); const { deviceType } = await import("document:configuration");
but this is not much of a win.
-
Alternately, we could try to specify a semantic where if the element with such an ID doesn't exist yet, we wait until it does before finishing module resolution. This would be nice to use, but it breaks some existing properties of modules, such as how they execute in order. I.e., we would have to delay the resolution and fetching of
script.mjs's dependencies until an element with the appropriate ID appears in the tree, and then we would have to go skip the usual ordering to execute that element's inline script (and any dependencies) immediately. Or, we could end up waiting indefinitely, if no such element appears. Also, these strange semantics an be caused deep in the tree, by anyimportstatement. So this seems bad.
Combined with the idea that there might be speculative future HTML modules-related use cases for an exports property, per #2235, probably this alternative is not a good direction and we should do exports instead.
Details
We've said exports should be a promise. What about in the non-module script case? It could be a forever-pending promise, or a promise already resolved with null. Or maybe it could be null, instead of a promise? Web IDL might make the latter impossible currently...
This feature makes inline JSON and CSS modules useful. Should we consider allowing them at the same time?
/cc @whatwg/modules
Activity
bmeck commentedon Nov 24, 2021
Personally this seems a decent feature to add, but I would think having it vary between module and classic Scripts as a bit odd. If the getter resolves a Promise to a module namespace object it is somewhat handy since it ~= the return type of
import(). Right now you cannot even reference a classic Script on the web viaimportin any form to my knowledge. I'd somewhat expect it to throw in that case since it simply isn't something you can do rather than something that is expected to be used.nullwould at least give errors when trying to access properties and expose a potential problem in a way that is actionable to fix, but a never ending Promise would just seem to hang, unresponsive.I don't have a strong preference but think whatever the value is seems fine due to
export function then() {}allowing it to be an arbitrary value rather than explicitly the namespace object if that makes sense.Kaiido commentedon Nov 26, 2021
Not my area of expertise, but for me one of the pain points of configuration objects as they work currently is the global's pollution and the possible conflicts between them.
From the examples here I have the impression that this problem would just be moved to the DOM element's ids map, since it seems libraries authors would still be responsible for defining the
"configuration"element's id.Also I find relying on authors to write
waitForElementcorrectly quite risky, there are many ways to mess this up, and it seems a bit sketchy to ask them to do so.So I was wondering if taking the problem the other way around and using an
importattribute could be a possible alternative, where authors would writeor even, by using same-document URL reference
I'm sure there are a lot of things involved here that I am missing, but as an author I think I'd prefer such a design, even if it means having to place my inline configuration script before the library's script.
domenic commentedon Nov 29, 2021
I think allowing any ordering is the key value of this proposal, so alternate solutions are best considered with that constraint in mind. See the "Alternative considered" section for another approach that doesn't meet that constraint, and why the authors who originated this proposal are not fond of it.
dvoytenko commentedon Nov 29, 2021
I think the proposal can address the global namespace problem and remove the need to author the
waitForElementcalls by hand. I'd approach it this way:await waitForElement('#configuration').exports.<script id="configuration" type="module"></script>tag.bmeck commentedon Nov 29, 2021
I'm a bit curious if there even is a global namespace problem given Shadow DOM. My main thought is if these can be injected as slots it seems to take away a bunch of the concerns, for example:
This likely would still need some glue if using something like a generic CDN since I'm not familiar with how this could let
x-editoreasily just include a<script>from a CDN without snooping around to find the root but it does seem doable even without needing a pre-processing step.Kaiido commentedon Nov 30, 2021
I have trouble to see why it's so hard to maintain the ordering of two script elements that it would dismiss any other issues with the presented use-case. Could you share an example scenario?
To be clear, the
import=""proposition would require this ordering only for inline scripts, and from what I can tell it wouldn't be affected byasync="", all that matters is that the element is already in the DOM when parsing the same-document URL referenceimport="#my-config".For external references
import="./config.mjs"there is no ordering problem, the external file is fetched just as if there was an actualimport * as config from "LOCAL_PATH/config.mjs"in the CDN servedscript.mjs.devsnek commentedon Nov 30, 2021
I like this proposal a lot, especially since it can easily match the return value of import(). I think personally the script case being wrapped up in the promise makes sense to me, since you can then handle that logic the same way. if you want to check "synchronously" you can read the element's type attribute right?
hiroshige-g commentedon Jan 5, 2022
Some random thoughts...
Another alternative in my mind is
#prepare-a-script, an inline module script withid=foois added to the module map with the URLdocument:foo.foohere is the id attribute of the script element at the time of#prepare-a-script.import { deviceType } from "document:foo";, then the specifier is resolved immediately todocument:foo(using ordinal absolute-URL parsing). If an inline script withid=foois not yet added to the DOM (i.e. there are no entries fordocument:fooin the module map), fetching (rather than specifier resolution) waits fordocument:footo appear in the module map, just like waiting for external scripts.This is to give names to inline scripts on the module maps, and is somewhat similar to the second one of "Alternative considered". This alleviates some of the concerns (e.g. module fetching is more regularly working and isn't blocked by to-be-added inline scripts), while sharing the other concerns. For example, the following scripts result in
2 1in the console, altering the inline module script evaluation order byimport 'document:foo'.(Also this looks like fetching
document:foofrom HTML/DOM, which might look like layering violation, while in its details this is purely implemented in the HTML spec.)hiroshige-g commentedon Jan 5, 2022
Some other (minor) thoughts on exposing
scriptElement.exports:scriptElement.exportsadds a new case where DOM mutations after#prepare-a-scriptare not no-op for script evaluations (e.g. id attribute changes).<script type="module" id="configuration">is added and evaluated in the main Document and then moved to an iframe, what should theexportsvalue of the script element be? (Probably it should be null or other invalid values, while the script evaluation itself isn't canceled).domenic commentedon Jan 5, 2022
The reason this is being brought up is based on sites maintained by multiple teams, where the final HTML document is assembled via many layers in the stack (e.g. framework, application developers, server-injected HTML, and even CDN-injected changes). The value proposition of this proposal is allowing dependencies to cross these layers without the different teams having to cooridnate on an ordering.
domenic commentedon Jan 5, 2022
Yeah, this seems unfortunate to me.
I don't quite understand this point. There are tons of DOM mutations after prepare-a-script that impact the rest of the page, if the rest of the page is inspecting the
HTMLScriptElement's JavaScript properties. For example, changingidorclassDOM attributes will change what theidandclassproperties return.Hmm. I'd be happy to null out the value in such cases, just because generally I find moving scripts between documents to be problematic and am happy to cripple those cases as much as possible (like we've already done for fetching). But I'm not sure I see it as being very important. That is, I don't think anything bad would happen if we continued to expose the same value for
exports.domenic commentedon Jan 5, 2022
Hmm. Upon reconsidering maybe it's not terrible. We can already get a similar effect today, where an
importstatement in one module "reorders" the execution of other modules on the page, in this sort of scenario:i.e. this will output 2 1 in a similar fashion.
The remaining problem is that it's much easier to indefinitely hang your application this way. The failure case where
import "./something.mjs"doesn't have a corresponding file on the server will quickly cause the module graph to error out. But the failure case whereimport "document:something"doesn't have (and never has) a corresponding element in the DOM will cause the module graph to hang indefinitely. (Or until some timeout, which I guess we could spec, but that doesn't sound great for page load predictability.)I'd be curious to hear others' thoughts. It certainly is a nice bit simpler to do
import { deviceType } from "document:configuration"than doconst { deviceType } = await (await waitForElement("#configuration")).exports;. In particular it would remove the need for a Babel plugin mentioned in #7367 (comment).dvoytenko commentedon Jan 29, 2022
@domenic I think either option is good. Some Babel plugin work would be required in either case. I do think that
scriptElement.exportshas a generic value beyond this use case.justinfagnani commentedon Aug 28, 2023
Are there any thoughts on how to make progress here?
Accessing a module is pretty important for use cases like declarative components: #2235 (comment)
justinfagnani commentedon Mar 23, 2024
It's very difficult to polyfill declarative custom elements that allow customization via script, or to implement Vue-like single-file components, without this proposal.
Many of the userland implementation have a roughly similar shape:
but the only way to get to the "export" of the
<script>tag is to put them into some kind of global map:which is obviously cumbersome and error-prone.
The proposal to add an
exportsPromise on the script tag seems pretty simple, obvious, and immediately useful to me. Could it move forward separately from any feature to import from the document?keithamus commentedon Mar 23, 2024
I’d be happy to prototype this in a browser, with blessing from a vendor representative.
ChrisShank commentedon Apr 9, 2025
Totally could see the
exportsproperty useful! I've also been wondering if the more general idea to aim for is a self-contained JS module system. Hash modules might be a suitable name since they can be reference by theiridattribute. If we add a new type for script tags it would be possible to polyfill with import maps and blob URLs.LeaVerou commentedon Jul 10, 2025
I think this is useful in its own right, but the DX of using this for configuration seems …atrocious, especially given the timing issues. And doesn't cover a big chunk of use cases: how do you pass configuration when importing via script?
From an architectural pov, HTML should not be required to pass configuration to a JS module.
I wonder if we could solve this in two passes:
import(in TC39). There are two subproblems here:For 1.i, the obvious way is to extend import attributes to support an attribute that passes data to the module. The data could be restricted to JSON-compatible data or or anything compatible with the structured clone algorithm.
1.ii is a quite tricky. In the simple case, the data could be available on
import.metaand that's the end of it. But what happens when the same module is imported from multiple places?Some alternatives might be:
import.metawith an Observable/EventTarget or other type of pubsub API, allowing authors to choose when or if to be notified. Then, aconfigevent can be fired with every new import that passes data and authors can choose how to handle multiple configs.Not a huge fan of any of these. Maybe someone else has a better idea.
2 seems relatively simple comparatively. Some ideas:
<script>element content for that, which is currently unused.justinfagnani commentedon Jul 10, 2025
I think for the use cases that involve granular customization - like configuring the behavior of specific tags - the DX is pretty good - it's a query and an await:
For this kind of construction:
h-define-elementjust needs to:That seems very reasonable to me, and critically there's no way to do this right now without a build step.
mariusGundersen commentedon Aug 6, 2025
I think this proposal,
scriptElement.exports, is a lot more useful for custom elements than for configuration. The initial example has several flaws and potentially better ways of doing it. For example, how long does the script wait for the configuration element to appear? What if the configuration is never added to the page? What if it is added long after page load? Therefore I don't think we should look at how to solve configuration.Currently there is no way to get the exports from
<script type="module">element, which this proposal would solve. How people use this is up to them, and there are many userland ways to find the right script, so as long as the exports are available people will figure it out.What should happen when you access
.exportsfrom a non-module script element? If returningnullis difficult then what about a rejected promise?DanielHerr commentedon Feb 4, 2026
It would be nice to leave undefined so that it could be defined as a regular property inside classic scripts.
LeaVerou commentedon Mar 18, 2026
I don't see why we'd null it? To be able to move it to another document, origins must already be compatible, so it seems pretty safe to just keep it? You'd just get values from another realm, but that's expected.