Currently, the advised way to feature-detect support for new Worker({type: "module"}) is to create an options object and see if the .type property gets accessed by the constructor with a getter:
let supportsModuleWorker = false;
const options = {
get type() {
supportsModuleWorker = true
}
};
new Worker("data:,", options).terminate();
That seems fairly convoluted. I propose adding type property to module instances:
const w = new Worker("data:,", {type: "module"})
const supportsModuleWorker = "type" in w;
w.terminate();
Ideally the property would be a getter defined on the Worker interface itself, which would make testing for it even cheaper:
const supportsModuleWorker = 'type' in Worker.prototype;
This might also be useful for other things aside from checking for support - there might be cases where a Worker is used to load scripts dynamically, and the caller needs to have knowledge of this in order to pass the correct value (a module or classic script URL, perhaps).
The feature detection snippet you post doesn't seem particularly "hard" to me, and matches how feature detection works for every other option-accepting API in the platform. I think this is not worth the extra work.
One complaint with feature detection in general is that its costly. Being able to feature detect module support without having to pay the cost to spin up a worker seems beneficial.
matches how feature detection works for every other option-accepting API in the platform
Personally, I wasn鈥榯 aware that this was a pattern at all. I find it quite unpleasant. But that might just be me then :D
I would want to +1 @wanderview鈥檚 comment (and @developit鈥檚 suggestion) that if we can avoid spinning up a worker to detect support, that鈥檇 be nice.
If we add a new value to type, how would you check support without (potentially) spinning up a worker? The suggestions without terminate() only work for this one-off transition. (And even if we did add it, those wanting to support earlier browsers with module worker support would end up with an even more convoluted check.)
(It's unfortunate that t sorts after n, otherwise you could throw from the name getter to avoid instantiation.)
Most helpful comment
Ideally the property would be a getter defined on the Worker interface itself, which would make testing for it even cheaper:
This might also be useful for other things aside from checking for support - there might be cases where a Worker is used to load scripts dynamically, and the caller needs to have knowledge of this in order to pass the correct value (a module or classic script URL, perhaps).