proposal-built-in-modules icon indicating copy to clipboard operation
proposal-built-in-modules copied to clipboard

Future extension to support lazy built-in module loading

Open littledan opened this issue 5 years ago • 4 comments

Normal JS modules only execute their top-level statements if someone imports them. In this proposal, if you want to polyfill built-in modules, you have to call BuiltinModule.export eagerly, just in case, and maybe that work will be wasted. This seems like a reasonable option for an MVP, so I support this proposal going to Stage 2 as is.

If we wanted to support a future extension for lazy built-in module polyfilling, we could make an alternative export API--call it BuiltinModule.exportLazy, which expects a callback, which is called at most one time, that returns the exports object. This callback will be called by the system when/if anyone imports the module--whether though BuiltinModule.import(), an import statement, or a dynamic import(). If polyfill authors decide to use this API, it could improve load performance by executing less code.

littledan avatar Sep 13 '20 16:09 littledan

Polyfilling is rarely as simple as “it’s absent, here’s a replacement” - it quite often requires inspecting the existing builtin and selectively polyfilling/wrapping/patching it. In practice i don’t think there would be a measurable benefit from optimizing for this rare use case (when you don’t need the runtime value in order to decide what to polyfill)

ljharb avatar Sep 13 '20 16:09 ljharb

I guess it probably depends on the case. I understand that some polyfills aim to add features added over time or correct browser bugs. I believe others don't, and just try to fill in the feature overall. Anyway, even if you're wrapping, I think it would make sense to do this lazily--we'd just have to make sure that the "underlying"/previous module is sent as a parameter to the callback. This only really falls over if you have a bunch of interdependent modules (which I admit may happen over time).

As I said, I'm fine with this API being a follow-on proposal, or deprioritized completely, but I wanted to talk about this possibility, just to make sure that built-in modules would be future-proofed against this possibility.

littledan avatar Sep 13 '20 17:09 littledan

I really like @littledan's suggestion of being able to lazily define builtins - this seems like it could make platform boot time much faster in not needing to initialize entire components of the platform until explicitly needed.

guybedford avatar Sep 13 '20 21:09 guybedford

I think this is a must for this proposal. #67 might be a solution for this

Jack-Works avatar Sep 24 '20 03:09 Jack-Works