Skip to content

ntnyq/browser-preloader

Repository files navigation

browser-preloader

CI NPM VERSION NPM DOWNLOADS LICENSE

Preload resources in browser, e.g: images.

Install

npm install browser-preloader
yarn add browser-preloader
pnpm add browser-preloader

Usage

import { 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()

API

preloadImages

  • Type: (images: string | string[], options: PreloadImagesOptions = {}) => Promise<HTMLImageElement[]>

Preload images in browser. The promise resolves with successfully loaded images.

preloadImagesSettled

  • Type: (images: string | string[], options: PreloadImagesOptions = {}) => Promise<PreloadImagesSettledResult>

Preload images in browser and return both successful images and failure details.

Parameters

images

  • Type: string | string[]

Array of image URLs or a single image URL.

options

  • Type: PreloadImagesOptions
  • Required: false

Options for preloading images, see PreloadImagesOptions in Interfaces.

Behavior Notes

  • Failed, timed out, or aborted images are omitted from preloadImages results.
  • Use preloadImagesSettled when you need { loaded, failed }.
  • maxConcurrent only affects strategy: 'parallel'; sequential loading always processes one image at a time.
  • signal cancels pending image loads. Already loaded images remain in the returned result.

Interfaces

/**
 * 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
   * @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
   *
   * @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
   */
  signal?: AbortSignal
}

export interface PreloadImageFailure {
  error: Error
  url: string
}

export interface PreloadImagesSettledResult {
  failed: PreloadImageFailure[]
  loaded: HTMLImageElement[]
}

License

MIT License © 2025-PRESENT ntnyq

About

📦 Preload resources in browser, e.g: images.

Topics

Resources

License

Stars

0 stars

Watchers

1 watching

Forks

Packages

 
 
 

Contributors