Preload resources in browser, e.g: images.
npm install browser-preloaderyarn add browser-preloaderpnpm add browser-preloaderimport { preloadImages, preloadImagesSettled } from 'browser-preloader'
// Basic usage
const loadedImages = await preloadImages(['foo.jpg', 'bar.png'])
console.log(`Loaded ${loadedImages.length} images`)
// Collect successful images and failure details
const result = await preloadImagesSettled(['foo.jpg', 'missing.png'])
console.log(result.loaded, result.failed)
// With callbacks
preloadImages(['foo.jpg', 'bar.png'], {
timeout: 5000,
onProgress(loaded, total) {
console.log(`Progress: ${loaded}/${total}`)
},
onComplete(images) {
console.log(`Successfully loaded: ${images.length}`)
},
onError(err, url) {
console.log(`Image ${url} failed to load`, err)
},
})
// Load images when browser is idle
preloadImages(['foo.jpg', 'bar.png'], {
loadOnIdle: true,
idleTimeout: 2000,
})
// Parallel loading with limited concurrency
preloadImages(['foo.jpg', 'bar.png', 'baz.jpg'], {
maxConcurrent: 2,
strategy: 'parallel',
})
// Sequential loading
preloadImages(['foo.jpg', 'bar.png', 'baz.jpg'], {
strategy: 'sequential',
})
// With cross-origin support
preloadImages(['https://example.com/image.jpg'], {
crossOrigin: true,
crossOriginAttribute: 'anonymous',
})
// With browser image hints
preloadImages(['hero.jpg'], {
decoding: 'async',
fetchPriority: 'high',
referrerPolicy: 'no-referrer',
})
// Cancel pending image loads
const controller = new AbortController()
preloadImages(['foo.jpg', 'bar.png'], {
signal: controller.signal,
})
controller.abort()- Type:
(images: string | string[], options: PreloadImagesOptions = {}) => Promise<HTMLImageElement[]>
Preload images in browser. The promise resolves with successfully loaded images.
- Type:
(images: string | string[], options: PreloadImagesOptions = {}) => Promise<PreloadImagesSettledResult>
Preload images in browser and return both successful images and failure details.
- Type:
string | string[]
Array of image URLs or a single image URL.
- Type:
PreloadImagesOptions - Required:
false
Options for preloading images, see PreloadImagesOptions in Interfaces.
- Failed, timed out, or aborted images are omitted from
preloadImagesresults. - Use
preloadImagesSettledwhen you need{ loaded, failed }. maxConcurrentonly affectsstrategy: 'parallel'; sequential loading always processes one image at a time.signalcancels pending image loads. Already loaded images remain in the returned result.- Cancellation also ends queued idle waits. Remaining URLs are reported as aborted without scheduling further idle callbacks.
- Synchronous exceptions from
onProgressoronErrorduring image events or timeouts do not prevent image loading from settling. They still propagate from the event or timeout callback and are not converted into image failures. Exceptions fromonCompletereject the returned promise.
/**
* Options for the {@link preloadImages} function
*/
export interface PreloadImagesOptions {
/**
* Whether to set the cross-origin attribute on the image
*
* @default false
*/
crossOrigin?: boolean
/**
* The cross-origin attribute to use for the image
*
* @default `anonymous`
*/
crossOriginAttribute?: 'anonymous' | 'use-credentials'
/**
* Image decoding hint
*/
decoding?: HTMLImageElement['decoding']
/**
* Image fetch priority hint
*/
fetchPriority?: HTMLImageElement['fetchPriority']
/**
* Timeout for requestIdleCallback in milliseconds
* Only effective when loadOnIdle is true
*
* @default 2000
*/
idleTimeout?: number
/**
* Whether to load images only when browser is idle
* Uses requestIdleCallback API if available
*
* @default false
*/
loadOnIdle?: boolean
/**
* Maximum number of concurrent image loads
*
* @default 6
*/
maxConcurrent?: number
/**
* The strategy to load images
*
* @default `parallel`
*/
strategy?: 'parallel' | 'sequential'
/**
* Timeout for image loading in milliseconds
*
* @default 0
*/
timeout?: number
/**
* Callback function to be called when all images are loaded
* @param loadedImages - Array of loaded HTMLImageElement objects
*/
onComplete?: (loadedImages: HTMLImageElement[]) => void
/**
* Callback function to be called when an error occurs
* Exceptions from this callback do not prevent an active image from settling
* @param error - Error object
* @param url - The URL of the image that failed to load
*/
onError?: (error: Error, url: string) => void
/**
* Callback function to be called when the progress of image loading changes
* Exceptions from this callback do not prevent an active image from settling
*
* @param loadedCount - Number of images loaded so far
* @param totalCount - Total number of images to be loaded
*/
onProgress?: (loadedCount: number, totalCount: number) => void
/**
* Image referrer policy
*/
referrerPolicy?: HTMLImageElement['referrerPolicy']
/**
* Signal for canceling pending image loads
* Also cancels queued idle waits
*/
signal?: AbortSignal
}
export interface PreloadImageFailure {
error: Error
url: string
}
export interface PreloadImagesSettledResult {
failed: PreloadImageFailure[]
loaded: HTMLImageElement[]
}