Skip to main content

Preloading

Loading an ad takes time, so show ads you loaded earlier. AdPreloader keeps one ad of any full-screen format ready.

import { AdPreloader, Admob, InterstitialAd } from 'nitro-ui-admob'

const interstitials = new AdPreloader(
() => InterstitialAd.load(Admob.testAdUnitId('interstitial')),
(error) => console.warn('Interstitial failed to load', error),
)
interstitials.start()

// At a natural break:
interstitials.take()?.show()

What it does​

After start(), the preloader:

  1. Loads an ad with your load function.
  2. Holds it until you call take(), then loads the next one.
  3. Drops the ad when its expiresAt passes and loads a fresh one.
  4. On a failed load, calls onLoadError and retries after 5 seconds, doubling the delay up to 5 minutes. A successful load resets the delay.
MemberDescription
start()Starts loading. Calling it again does nothing.
take()Returns the ready ad, or undefined if none is ready, and starts loading the next one.
isReadyWhether take() would return an ad: one is loaded and not expired.
stop()Stops loading, cancels a pending retry and drops the ready ad.

In a component​

Create the preloader once and stop it on unmount:

import { useEffect, useState } from 'react'
import { AdPreloader, InterstitialAd } from 'nitro-ui-admob'

function useInterstitials(adUnitId: string) {
const [preloader] = useState(() => new AdPreloader(() => InterstitialAd.load(adUnitId)))
useEffect(() => {
preloader.start()
return () => preloader.stop()
}, [preloader])
return preloader
}

take() hands the ad to you: assign its callbacks before calling show(). App open ads have a ready-made wrapper, startAppOpenAds.