diff --git a/src/CustomAttributeRegistry.ts b/src/CustomAttributeRegistry.ts index 05644c1..a548740 100644 --- a/src/CustomAttributeRegistry.ts +++ b/src/CustomAttributeRegistry.ts @@ -136,16 +136,3 @@ export interface CustomAttribute { disconnectedCallback?(): void changedCallback?(oldValue: string, newValue: string): void } - -// Avoid errors trying to use DOM APIs in non-DOM environments (f.e. server-side rendering). -if (globalThis.window?.document) { - const original = Element.prototype.attachShadow - - Element.prototype.attachShadow = function attachShadow(options) { - const root = original.call(this, options) - - if (!root.customAttributes) root.customAttributes = new CustomAttributeRegistry(root) - - return root - } -} diff --git a/src/index.ts b/src/index.ts index 5d766f1..ffe6e30 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,7 +9,19 @@ export * from './CustomAttributeRegistry.js' export let customAttributes: CustomAttributeRegistry // Avoid errors trying to use DOM APIs in non-DOM environments (f.e. server-side rendering). -if (globalThis.window?.document) customAttributes = globalThis.customAttributes = new CustomAttributeRegistry(document) +if (globalThis.window?.document) { + customAttributes = globalThis.customAttributes = new CustomAttributeRegistry(document) + + const originalAttachShadow = Element.prototype.attachShadow + + Element.prototype.attachShadow = function attachShadow(options) { + const root = originalAttachShadow.call(this, options) + + if (!root.customAttributes) root.customAttributes = new CustomAttributeRegistry(root) + + return root + } +} declare global { // const doesn't always work (TS bug). At time of writing this, it doesn't work in this TS playground example: