All Projects → dmnsgn → async-preloader

dmnsgn / async-preloader

Licence: MIT license
Assets preloader using ES2017 async/await and fetch.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
HTML
75241 projects

Projects that are alternatives of or similar to async-preloader

Sinn
a blog based on of react,webpack3,dva,redux,material-ui,fetch,generator,markdown,nodejs,koa2,mongoose,docker,shell,and async/await 基于react+koa2技术栈的个人开源博客系统
Stars: ✭ 175 (+297.73%)
Mutual labels:  fetch, async-await
Create React Redux App
This project was bootstrapped with Create React App and Redux, Sass Structure.
Stars: ✭ 46 (+4.55%)
Mutual labels:  fetch, async-await
AsyncTcpClient
An asynchronous variant of TcpClient and TcpListener for .NET Standard.
Stars: ✭ 125 (+184.09%)
Mutual labels:  async-await
async-await-codemod
Codemod script for migrating promise-based functions to use async/await syntax
Stars: ✭ 22 (-50%)
Mutual labels:  async-await
sysfex
Another system information fetching tool written in C++
Stars: ✭ 107 (+143.18%)
Mutual labels:  fetch
auto-async-wrap
automatic async middleware wrapper for expressjs errorhandler.
Stars: ✭ 21 (-52.27%)
Mutual labels:  async-await
is-async-supported
Check if async/await is available natively
Stars: ✭ 16 (-63.64%)
Mutual labels:  async-await
async
Asynchronous programming for R -- async/await and generators/yield
Stars: ✭ 37 (-15.91%)
Mutual labels:  async-await
conquerant
lightweight async/await for Clojure
Stars: ✭ 31 (-29.55%)
Mutual labels:  async-await
gotify-push
Chrome Extension for Send Push Notification 🔔 to gotify/server ☁
Stars: ✭ 32 (-27.27%)
Mutual labels:  fetch
beccaccino
Beccaccino is an easy, sexy, reliable, framework agnostic http client for redux that is ⚡️beccaccino fast!
Stars: ✭ 13 (-70.45%)
Mutual labels:  fetch
koa2-example-app
An app that is built using koa2 and async/await
Stars: ✭ 85 (+93.18%)
Mutual labels:  async-await
react-sync
A declarative approach to fetching data via a React higher order component
Stars: ✭ 18 (-59.09%)
Mutual labels:  fetch
tempdb
Redis-backed ephemeral key-value store for Node
Stars: ✭ 30 (-31.82%)
Mutual labels:  async-await
sysfetch
A super tiny system information fetch script written in BASH
Stars: ✭ 197 (+347.73%)
Mutual labels:  fetch
xhttp
Tiny shortcuts for using the native fetch API. Provides a fluent builder-style API for request building and response reading.
Stars: ✭ 31 (-29.55%)
Mutual labels:  fetch
miniprogram-network
Redefine the Network API of Wechat MiniProgram (小程序网络库)
Stars: ✭ 93 (+111.36%)
Mutual labels:  fetch
i18next-http-backend
i18next-http-backend is a backend layer for i18next using in Node.js, in the browser and for Deno.
Stars: ✭ 270 (+513.64%)
Mutual labels:  fetch
eslint-config-welly
😎 ⚙️ ESLint configuration for React projects that I do. Feel free to use this!
Stars: ✭ 21 (-52.27%)
Mutual labels:  async-await
parcel-plugin-goodie-bag
provides the Promise and fetch goodies needed for IE(11) support w/ parcel bundle loading
Stars: ✭ 15 (-65.91%)
Mutual labels:  fetch

async-preloader

npm version stability-stable npm minzipped size dependencies types Conventional Commits styled with prettier linted with eslint tested with jest license

Assets preloader using ES2017 async/await and fetch.

paypal coinbase twitter

Install

npm install --save async-preloader

Documentation

Quick start

This section covers the basic usage of AsyncPreloader. For more informations about async/await, see Async functions - making promises friendly. Usage in Node.js environment is limited to its capacity to handle fetch requests. Polyfills like node-fetch and xmldom might come handy.

Preload items and retrieve them

import AsyncPreloader from "async-preloader";

const items = [
  { 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: "myDefaultXmlFile", src: "assets/xml", loader: "Xml" },
  { id: "myFont", src: `assets/font.ttf` },
  { id: "Space Regular", loader: "Font", fontOptions: { timeout: 10000 } },
  // Can be retrieved with the src property eg. AsyncPreloader.items.get("assets/fileWithoutId")
  { src: "assets/fileWithoutId" },
];

// Pass an array of LoadItem
//
// Returns a Promise with an array of LoadedValue
const pItems = AsyncPreloader.loadItems(items);

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 will try to detect the font in the page using FontFaceObserver when no src is specified.

Load items from a manifest file

It works in a similar fashion as createjs's PreloadJS.

import AsyncPreloader from "async-preloader";

// Pass the file url and an optional path of the property to get in the JSON file.
// It will load the file using the Json loader and look for the path key expecting an array of `LoadItem`s.
// Default path is "items" eg the default manifest would look like this:
// `{ "items": [ { "src": "assets/file1" }, { "src": "assets/file2" }] }`
//
// Returns a Promise with an array of LoadedValue
const pItems = AsyncPreloader.loadManifest(
  "assets/manifest.json",
  "data.preloader.items"
);

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

Advanced usage

This section takes a closer look at the options of AsyncPreloader.

Load a single item by using the loaders directly

import AsyncPreloader from "async-preloader";

// Pass a LoadItem
//
// Returns a Promise with the LoadedValue
const pItem = AsyncPreloader.loadJson({ src: "assets/json.json" });

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

Note: Using the loaders directly won't add the item to the items Map. Alternatively you could use AsyncPreloader.loadItem and rely on the file extension or add { loader: "Json"} to the item.

Get an ArrayBuffer instead of the default Blob

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

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

import AsyncPreloader from "async-preloader";

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

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

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";

const items = [
  { id: "myDefaultFile", src: "assets/default" }, // ...
];

let loadedCount = 0;

async function preload() {
  await Promise.all(
    items.map(async (item) => {
      const data = await AsyncPreloader.loadItem(item);
      loadedCount++;
      console.log(`Progress: ${(100 * loadedCount) / items.length}%`);
    })
  );
}

await preload();

Abort one or more loadItem(s) request(s)

To abort a loadItem(s) call, you can create an AbortController instance and pass its signal to options.

const controller = new AbortController();

const timeoutId = setTimeout(() => {
  controller.abort();
}, 150);

try {
  await AsyncPreloader.loadItems(
    items.map((item) => ({
      ...item,
      options: { ...(item.options || {}), signal: controller.signal },
    }))
  );
} catch (error) {
  if (error.name === "AbortError") console.log("Request was aborted");
} finally {
  clearTimeout(timeoutId);
}

Note: the example above uses the async functions (which is the core of this module). You'll need to transpile it if you are targeting older browsers (namely IE11). See support here.

License

MIT © Damien Seguin

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].