Prefetch
Pre-load ads before they’re needed to reduce latency and improve user experience.
Basic Usage
import Ads from 'notpixel';
const ads = new Ads({
publisherId: 'pub-xxx',
cache: true,
});
// Prefetch ads for likely queries
await ads.prefetch([
'how to deploy',
'best practices',
'getting started',
]);
// Later, these calls hit cache (fast!)
const ad = await ads.getAd({ input: 'how to deploy' });Single Input
await ads.prefetch('upcoming query');Multiple Inputs
const result = await ads.prefetch([
'query 1',
'query 2',
'query 3',
]);
console.log(result.prefetched); // 3
console.log(result.failed); // 0
console.log(result.latencyMs); // 150Fire and Forget
Prefetch in the background without waiting:
// Don't await - just fire and forget
ads.prefetch(['q1', 'q2', 'q3']).catch(() => {});
// Continue with other work...Options
await ads.prefetch('query', {
publisherId: 'override-pub', // Optional publisher ID override
});Auto-Enable Cache
If cache is not enabled, prefetch() automatically enables it. This ensures prefetched ads are available for later retrieval.
// Cache not explicitly enabled
const ads = new Ads({ publisherId: 'pub-xxx' });
// Prefetch enables cache automatically
await ads.prefetch('query');
// Cache is now available
console.log(ads.cache.stats().enabled); // trueUse Cases
App Startup
Pre-fetch ads for common queries when your app loads:
async function initApp() {
const ads = new Ads({ publisherId: 'pub-xxx', cache: true });
// Prefetch in background
ads.prefetch([
'getting started',
'installation',
'quick start',
'tutorial',
]).catch(console.error);
// Continue app initialization...
}Predictive Prefetching
Prefetch based on user behavior:
function onUserTyping(partialQuery: string) {
// Predict likely completions
const predictions = predictCompletions(partialQuery);
// Prefetch ads for predictions
ads.prefetch(predictions).catch(() => {});
}Conversation Context
Prefetch ads for related topics:
async function onNewMessage(topic: string) {
// Get related topics
const relatedTopics = getRelatedTopics(topic);
// Prefetch in background
ads.prefetch(relatedTopics);
// Process current message...
}Deduplication
Prefetch automatically deduplicates requests:
// These 3 identical inputs only make 1 API call
await ads.prefetch(['same query', 'same query', 'same query']);Response Type
interface PrefetchResult {
prefetched: number; // Successfully prefetched
failed: number; // Failed to prefetch
latencyMs: number; // Total time
}Best Practices
- Prefetch early: Call prefetch as soon as you know what queries are likely
- Fire and forget: Don’t block on prefetch completion unless necessary
- Limit scope: Only prefetch 5-10 queries at a time
- Handle errors: Always catch prefetch errors to avoid unhandled rejections