> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wearo.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Async loading patterns

> Load the Wearo widget asynchronously without race conditions.

# Async loading patterns

## When to use the queue pattern

Use it when:

* You add `async` or `defer` to the `<script>` tag
* The script is in `<head>` but `init()` is called in `<body>`
* You're loading via Google Tag Manager (GTM defers execution by default)

If both the `<script src="...">` and `TryOnWidget.init()` are at the end of `</body>` without `async`/`defer`, **you don't need this pattern**.

## The queue pattern

```html theme={"dark"}
<!-- Initialize the queue BEFORE the script loads -->
<script>
  window.TryOnWidgetQueue = window.TryOnWidgetQueue || [];
  window.TryOnWidgetQueue.push({
    method: 'init',
    config: {
      apiKey: 'wearo_xxxxxxxxxxxxxxxxxxxx',
      productSelector: 'img[data-product-image]'
    }
  });
</script>

<!-- Load the script asynchronously -->
<script src="https://wearo.io/widget/tryon-widget.js" async></script>
```

The loader automatically drains the queue at boot — `init()` will be called exactly once, regardless of load order.

## GTM Custom HTML tag

In GTM, use the queue pattern so the config is ready before the script executes:

```html theme={"dark"}
<script src="https://wearo.io/widget/tryon-widget.js" async></script>
<script>
  window.TryOnWidgetQueue = window.TryOnWidgetQueue || [];
  window.TryOnWidgetQueue.push({
    method: 'init',
    config: {
      apiKey: 'wearo_xxxxxxxxxxxxxxxxxxxx',
      productSelector: '.product__media img',
      brandColor: '#000000'
    }
  });
</script>
```

No other changes needed — the widget API is identical whether loaded via GTM or a direct script tag.
