whenCustomElementDefined function
Asynchronously waits for a custom element tag to be registered and upgraded in the browser's CustomElementRegistry.
Calls window.customElements.whenDefined(tag) to ensure that the custom element's
class definition has been loaded and registered before interacting with its DOM properties.
Graceful Timeout Handling
If the custom element is already registered, the returned Future completes immediately.
If the definition has not yet loaded (e.g. while an external script is fetching asynchronously),
it waits up to timeout (defaulting to 3 seconds). If the timeout expires before registration
occurs, it completes gracefully rather than throwing or hanging indefinitely.
await whenCustomElementDefined('sl-button', timeout: const Duration(seconds: 2));
Implementation
Future<void> whenCustomElementDefined(
String tag, {
Duration timeout = const Duration(seconds: 3),
}) async {
try {
final promise = web.window.customElements.whenDefined(tag);
await promise.toDart.timeout(timeout);
} catch (_) {
// Timeout or whenDefined failure — continue gracefully
}
}