> For the complete documentation index, see [llms.txt](https://tads.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tads.gitbook.io/docs/getting-started/publishers/embed-widget/vanilla-js.md).

# Vanilla JS

## 1. Insert widget code in the app

You can integrate the widget using native JavaScript. Add the following code to your project, ensuring that the tads script is loaded beforehand:

{% stepper %}
{% step %}

#### Insert the following script into \<head> or in the end of \<body>  in your HTML document:

```html
<script src="https://w.tads.me/widget.js"></script>
```

{% endstep %}

{% step %}

#### Insert the following `<div>` where you want to render the ad (for the Text-Graphic Block only):

```html
<div id="tads-container-YOUR_WIDGET_ID"></div>
```

{% endstep %}

{% step %}

#### Add the following code for the selected format to your HTML document to initialize the widget:

### Text-Graphic Block (TGB)

```html
<script>
    const adsNotFoundCallback = () => {
        console.log('No ads found to show');
        // Write your code here in case we couldn't display ad
    };

    // Callback for REWARDED format
    const onClickRewardCallback = (adId) => {
        console.log('Clicked ad:', adId);
    };

    const adController = window.tads.init({
        widgetId: YOUR_WIDGET_ID,
        type: 'static',
        debug: false, // Use 'true' for development and 'false' for production
        onClickReward: onClickRewardCallback,
        onAdsNotFound: adsNotFoundCallback
    });

    adController.loadAd()
        .then(() => adController.showAd())
        .catch((err) => {
            console.log(err);
            adsNotFoundCallback();
        });
</script>
```

### Fullscreen banner

```html
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const WIDGET_ID = YOUR_WIDGET_ID; // number from your dashboard

        // Use 'true' for development and 'false' for production
        const IS_DEBUG = false;

        // The id of the HTML element (button or link) that opens the ad on click.
        const BUTTON_ID = "your_button_id";

        // Callback for REWARDED format: called after the user watches the whole ad.
        const onShowRewardCallback = (adId) => {
            console.log('Ad watched, reward the user:', adId);
        };

        // Called when there is no ad to show right now.
        const onAdsNotFound = () => {
            console.log('No ads found to show');
        };

        const adController = window.tads.init({
            widgetId: WIDGET_ID,
            type: 'fullscreen',
            debug: IS_DEBUG,
            onShowReward: onShowRewardCallback,
            onAdsNotFound: onAdsNotFound
        });

        // showAd() fetches the ad itself and opens the fullscreen overlay.
        // Do not call loadAd() before it: that would request the ad twice.
        document.getElementById(BUTTON_ID).addEventListener('click', () => {
            adController.showAd().catch((err) => {
                console.log(err); // e.g. "No ads to show" or "Too many fullscreen ads in short time"
            });
        });
    });
</script>
```

{% endstep %}
{% endstepper %}

<details>

<summary>Alternative widget code (async)</summary>

If you need to speed up page loading, you can use the alternative widget code that includes the `async` attribute. This setup method requires advanced setup and is recommended for experienced webmasters:

1. **Insert the following script into any place of your HTML document:**

```html
<script src="https://w.tads.me/widget.js" async></script>
```

2. **Insert the following `<div>` where you want to render the ad:**

```html
<div id="tads-container-YOUR_WIDGET_ID"></div>
```

3. **Add the following code  for the selected format after `<div>` to initialize the widget**

#### Text-Graphic Block (TGB)

```html
<script>
    const initTadsWidget = function() {
        const adsNotFoundCallback = () => {
            console.log('No ads found to show');
            // Write your code here in case we couldn't display ad
        };

        function initAdController() {
            const adController = window.tads.init({
                widgetId: YOUR_WIDGET_ID,
                debug: false, // Use 'true' for development and 'false' for production
                onShowReward: (adId) => {
                    console.log('Show ad:', adId);
                    // Write code here for reward user after ad showed or delete this func onShowReward
                },
                onClickReward: (adId) => {
                    console.log('Click on ad:', adId);
                    // Write code for reward user after ad cliked or delete this func onClickReward
                },
                onAdsNotFound: adsNotFoundCallback
            });

            adController.loadAd()
                .then(() => adController.showAd())
                .catch((err) => {
                    console.log(err);
                    adsNotFoundCallback();
                });
        }

        if (window.tads && window.tads.init) {
            initAdController();
        } else {
            let tadsInterval = setInterval(() => {
                if (window.tads && window.tads.init) {
                    clearInterval(tadsInterval);
                    initAdController();
                }
            }, 100);
        }
    };

    if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initTadsWidget);
    } else {
        initTadsWidget();
    }
</script>

```

#### Fullscreen banner

```html
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const WIDGET_ID = "YOUR_WIDGET_ID"; // Replace on your WIDGET ID
    const IS_DEBUG = true; // Replace on false in production
    const BTN_ID = "your_clickable_selector"; // Replace on your button ID
    const TYPE = "fullscreen";

    let adController = null;
    let tadsReady = false;

    const onShowRewardCallback = (result) => {
      console.log("Show ads, reward user:", result);
    };

    const onAdsNotFound = () => {
      console.log("No ads found to show");
    };

    function waitForTadsReady(timeout = 5000) {
      return new Promise((resolve, reject) => {
        if (window.tads && typeof window.tads.init === "function") {
          return resolve();
        }

        const start = performance.now();
        const iv = setInterval(() => {
          if (window.tads && typeof window.tads.init === "function") {
            clearInterval(iv);
            resolve();
          } else if (performance.now() - start > timeout) {
            clearInterval(iv);
            reject(new Error("TADS widget script not loaded"));
          }
        }, 50);
      });
    }

    async function showAd() {
      try {
        if (!tadsReady) {
          await waitForTadsReady();
          tadsReady = true;
        }

        if (!adController) {
          adController =
            window.tads.controllers?.[WIDGET_ID] ||
            window.tads.init({
              widgetId: WIDGET_ID,
              type: TYPE,
              debug: IS_DEBUG,
              onShowReward: onShowRewardCallback,
              onAdsNotFound: onAdsNotFound,
            });
        }

        if (adController && typeof adController.showAd === "function") {
          adController.showAd().catch((err) => {
            console.error(`Error showing ad:`, err);
          });
        } else {
          console.warn("Ad controller not ready");
        }
      } catch (err) {
        console.error("Failed to load TADS:", err);
      }
    }

    const btn = document.getElementById(BTN_ID);
    if (!btn) {
      console.error("Button not found:", BTN_ID);
      return;
    }

    btn.addEventListener("click", showAd);
  });
</script>
```

</details>

## 2. Add your widget ID&#x20;

Replace YOUR\_WIDGET\_ID with the corresponding widget ID you received from your personal account.

## 3. Set a reward (if needed)

If you want to incentivize users to view or click on the ads, add code to the `onShowRewardCallback` and `onClickRewardCallback` and `onAdsNotFound` functions to reward the user for viewing and/or clicking, respectively.\
You can config your widget using the following parameters

<table><thead><tr><th width="160">Parameter</th><th width="97"></th><th width="104">Type</th><th width="102">Default</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>required</td><td>string</td><td></td><td>Your widget ID that you received from your personal account</td></tr><tr><td>type</td><td>required</td><td>string</td><td>static</td><td>Type of your widget. It can be 'static' or 'fullscreen'</td></tr><tr><td>debug</td><td>optional</td><td>boolean</td><td>false</td><td>Flag which you can use for development mode (it doesn't collect data in your ads account and doesn't requests real ads)</td></tr><tr><td>onShowReward</td><td>optional</td><td>function</td><td>null</td><td>Callback which will be called after user watches ad</td></tr><tr><td>onClickReward</td><td>optional</td><td>function</td><td>null</td><td>Callback which will be called after user clicks ad</td></tr><tr><td>onAdsNotFound</td><td>optional</td><td>function</td><td>null</td><td>Callback which will be called if we don't find ads for user</td></tr></tbody></table>

##
