Skip to content

peterbenoit/ResourceLoader.js

Repository files navigation

ResourceLoader

ResourceLoader is a flexible JavaScript library that allows for dynamic loading of resources like JavaScript, CSS, images, JSON, and other file types. It supports features like error handling, retries, cache busting, and concurrency control, making it suitable for various applications.

Features

  • Dynamic Resource Loading: Load JS, CSS, images, JSON, fonts, and more dynamically.
  • Concurrency Control: Limit the number of concurrent loads to prevent overwhelming the browser.
  • Retries and Error Handling: Automatically retry failed resource loads, with customizable retry delays.
  • Cache Busting: Optionally append cache-busting query strings to prevent caching issues.
  • Cross-Origin and Integrity Handling: Support for crossorigin and integrity attributes for secure resource loading.
  • Blob and File Loading: Load and handle binary files like images, audio, and video as blobs.
  • Callbacks for Success and Failure: Handle success or failure for each resource with callbacks.

Installation

You can directly download the ResourceLoader.js file or include it from your project.

CDN Usage

Use jsDelivr (recommended) or unpkg directly from the npm package.

Pinned version:

<script src="https://cdn.jsdelivr.net/npm/resourceloader-js@1.0.1/resourceLoader.js"></script>

Latest published version:

<script src="https://cdn.jsdelivr.net/npm/resourceloader-js/resourceLoader.js"></script>

unpkg pinned version:

<script src="https://unpkg.com/resourceloader-js@1.0.1/resourceLoader.js"></script>

Direct Download

You can download the ResourceLoader.js file directly from this repository.

Usage

After including ResourceLoader.js in your HTML:

<script src="path/to/ResourceLoader.js"></script>

ResourceLoader will be available as a global object window.ResourceLoader or simply ResourceLoader in your code.

Demo

Some examples of ResourceLoader in action can be found at CodePen.

Usage

Include the ResourceLoader.js file in your HTML or project:

<script src="path/to/ResourceLoader.js"></script>

Example Usage

Basic JavaScript and CSS Loading

ResourceLoader.include(
    [
        'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js',
        'https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css',
    ],
    {
        logLevel: 'verbose',
    }
)
    .then(() => {
        console.log('Resources loaded successfully.');
    })
    .catch((error) => {
        console.error('Error loading resources:', error);
    });

JSON Loading

ResourceLoader.include(['https://example.com/data.json'], {
    onSuccess: (data) => {
        console.log('JSON data loaded:', data);
    },
    onError: (error, url) => {
        console.error(`Error loading JSON from: ${url}`, error.message);
    },
});

Image Loading

ResourceLoader.include(['https://example.com/image.jpg'], {
    onSuccess: (url) => {
        const img = new Image();
        img.src = url;
        document.body.appendChild(img);
        console.log('Image loaded successfully.');
    },
    onError: (error, url) => {
        console.error(`Error loading image from: ${url}`, error.message);
    },
});

Audio Loading as Blob

ResourceLoader.include(['https://example.com/audio.mp3'], {
    onSuccess: (data) => {
        const blobUrl = URL.createObjectURL(data);
        const audioElement = document.createElement('audio');
        audioElement.controls = true;
        audioElement.src = blobUrl;
        document.body.appendChild(audioElement);
    },
    onError: (error, url) => {
        console.error(`Error loading audio from: ${url}`, error.message);
    },
});

Cache Busting

ResourceLoader.include(['https://example.com/script.js'], {
    cacheBusting: true,
});

API

include(urls, options)

  • urls: An array of URLs or a single URL to be loaded.
  • options:
    • logLevel: (default 'warn') Log level. Can be 'silent', 'warn', or 'verbose'.
    • onSuccess: Callback when the resource(s) load successfully.
    • onError: Callback when the resource fails to load.
    • retries: Number of times to retry loading on failure.
    • retryDelay: Delay between retry attempts.
    • deferScriptsUntilReady: If true, defers script loading until DOM is ready.
    • maxConcurrency: Limit concurrent resource loads.
    • cacheBusting: Append a cache-busting query parameter to the resource URL.
    • crossorigin: Set cross-origin for JS/CSS resources.
    • attributes: Additional attributes to set on the element (e.g., integrity).

Returns a Promise that resolves with an array of per-resource results when all resources succeed:

[
    { status: 'fulfilled', value: 'https://example.com/script.js' },
];

If any resource fails, the Promise rejects with an aggregate error:

{
    type: 'aggregate',
    message: 'One or more resources failed to load.',
    results: [
        { status: 'fulfilled', value: 'https://example.com/good.css' },
        { status: 'rejected', reason: { type: 'network', message: '...' }, url: 'https://example.com/bad.css' }
    ]
}

unloadResource(url)

Unloads a resource from the page.

ResourceLoader.unloadResource('https://example.com/script.js');

cancelResource(url)

Cancels the loading of a resource.

ResourceLoader.cancelResource('https://example.com/script.js');

cancelAll()

Cancels all pending resource loads.

ResourceLoader.cancelAll();

getResourceState(url)

Gets the current state of a resource ("loading", "loaded", "unloaded").

const state = ResourceLoader.getResourceState('https://example.com/script.js');
console.log(state); // "loaded"

License

This project is licensed under the MIT License.

Testing

Run tests from the repository root:

npm install
npm test

Release Steps

Run the automated release helper from the repository root:

npm run release

No-flag mode starts an interactive wizard where you choose bump type and whether to publish.

Shortcut commands:

npm run release:patch
npm run release:minor
npm run release:major
npm run release:publish

Flag-driven mode is still available:

npm run release -- --bump patch --publish

What the release helper does:

  • Ensures the git tree is clean.
  • Verifies npm auth (npm whoami) and starts npm login if needed.
  • Runs npm test and npm run pack:dry-run.
  • Runs npm version <bump> (creates commit + tag).
  • Pushes with tags (git push origin HEAD --follow-tags).
  • Optionally runs npm publish.
  • Prints npm/CDN verification info.

Manual flow (equivalent):

npm install
npm version patch
npm test
npm run pack:dry-run
npm publish

If you need to publish a specific version bump, replace patch with minor or major.

About

ResourceLoader is a flexible JavaScript library that allows for dynamic loading of resources like JavaScript, CSS, images, JSON, and other file types. It supports features like error handling, retries, cache busting, and concurrency control, making it suitable for various applications.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors