Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

async-preloader

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

async-preloader

Assets preloader using ES2017 async/await and fetch.

  • 2.2.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

async-preloader

Build Status styled with prettier tested with jest

Assets preloader using ES2017 async/await and fetch.

Install

$ npm install --save async-preloader

API

LoadItem

interface LoadItem {
  id?: string;
  src: string;
  loader?: string;
  options?: object;
  body?: "arrayBuffer" | "blob" | "formData" | "json" | "text"
}
KeyDescription
idOptional id to retrieve the file using AsyncPreloader.items.get(id)
srcInput for the Fetch API
loaderOptional string from one of the LOADERS Map. It needs to be specified for Font and Audio (webm,ogg). Otherwise the loader is inferred from the file extension or default to Response.text() if there is no extension.
optionsOptional object to pass to the fetch method.
bodyOptional string to define the Body method to handle the Response. Default to blob() for Image, Video and Audio.

AsyncPreloader.items

A Map object containing the loaded items (keys being LoadItem.id if specified or LoadItem.src).

AsyncPreloader.loadItems(items: LoadItem[])

Arguments

items (Array): Array of LoadItems

Returns

(Promise): A Promise that resolves with the loaded items.

Example
import AsyncPreloader from "async-preloader";

const pItems = AsyncPreloader.loadItems([
  { "id": "myDefaultFile", "src": "assets/default"   },
  { "id": "myTextFile",    "src": "assets/text.txt"  },
  { "id": "myJsonFile",    "src": "assets/json.json" },
  { "id": "myImageFile",   "src": "assets/image.jpg" },
  { "id": "myVideoFile",   "src": "assets/video.mp4" },
  { "id": "myAudioFile",   "src": "assets/audio.mp3" },
  { "id": "myXmlFile",     "src": "assets/xml.xml"   },
  { "id": "mySvgFile",     "src": "assets/xml.svg"   },
  { "id": "myHtmlFile",    "src": "assets/xml.html"  },
  { "id": "myFont",        "src": "Open Sans Regular", "loader": "Font" }
]);

pItems
  .then(items => {
    const element = AsyncPreloader.items.get("myVideoFile");
    document.body.appendChild(element);
  })
  .catch(error => console.error("Error loading items", error));

Note: Font loader is using FontFaceObserver

AsyncPreloader.loadManifest(src: string)

You can also load a manifest file. It works in a similar fashion as createjs's PreloadJS.

Arguments

src (String): Input for the Fetch API. It will load the file using the JsonLoader and look for an "items" key containing an array of LoadItems.

Returns

(Promise): A Promise that resolves with the loaded items.

Example
import AsyncPreloader from "async-preloader";

const pItems = AsyncPreloader.loadItems("assets/manifest.json");

pItems
  .then(items => useLoadedItemsFromManifest(items)) // or AsyncPreloader.items.get(pathOrId)
  .catch(error => console.error("Error loading items", error));

AsyncPreloader.loadJson(item: LoadItem)

It is also possible to use the LOADERS individually.

Arguments

item (LoadItem): a LoadItem.

Returns

(Promise): A Promise that resolves with the loaded item.

Example
import AsyncPreloader from "async-preloader";

const pItem = AsyncPreloader.loadJson({ "src": "assets/json.json" });

pItem
  .then(item => useLoadedItem(item))
  .catch(error => console.error("Error loading item", error));

Usage

Getting the progress

Since fetch doesn't support Progress events yet, you might want to get a per file progress:

import AsyncPreloader from "async-preloader";

let loadedCount = 0;
async function preload() {
  await Promise.all(
    itemsToLoad.map(async item => {
      const data = await AsyncPreloader.loadItem(item);
      loadedCount++;
      console.log(loadedCount / itemsToLoad.length);
    })
  );
}
await preload();

Get an ArrayBuffer instead of a blob

You can specify how the response is handle by using the body key in a LoadItem.

Typical use case: use with the WebAudio API to decode the data with baseAudioContext.decodeAudioData():

import AsyncPreloader from "async-preloader";

const pItem = AsyncPreloader.loadAudio({ src: "assets/audio.mp3", body: "arrayBuffer" });

pItem
  .then(item => audioContext.decodeAudioData(item))
  .catch(error => console.error("Error decoding audio", error));

License

MIT © Damien Seguin

Keywords

FAQs

Package last updated on 22 Feb 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc