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:
- Loads an ad with your
loadfunction. - Holds it until you call
take(), then loads the next one. - Drops the ad when its
expiresAtpasses and loads a fresh one. - On a failed load, calls
onLoadErrorand retries after 5 seconds, doubling the delay up to 5 minutes. A successful load resets the delay.
| Member | Description |
|---|---|
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. |
isReady | Whether 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.