# resource/assetloader (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/resource/assetloader/

Loads assets together.

## AssetLoader extends Object

Loads assets together.
- Adds images, JSON, text, binary, sounds, fonts and custom loads (addTask) to the list and loads them all at once with load().
  The number of concurrent loads is set with setConcurrency. (Waiting for each one in turn delays loading and decoding in a queue)
- Failed ones also count as finished, so it does not stop. Failures remain in getFailedList() as { path, error }.
- Progress is finished count / total count. (getProgress, loaded count getLoadedCount, finished count getFinishedCount, total getTotalCount)
  Calls the function set with setProgressHandler on every change, and the function set with setCompleteHandler when everything is done.
- Items added while loading are also loaded by the same load. (If fewer workers are running than the concurrency, launches that many more) To add more after everything is done, call load() again.
- Usage:
    const assetLoader = new AssetLoader();
    assetLoader.setConcurrency(8);
    const titleImageAsset = assetLoader.addImage("assets/title.png");
    const stageJsonAsset = assetLoader.addJson("assets/stage.json");
    gameScene.trackAssetLoader(assetLoader);     // GameScene loading bar follows the progress
    await assetLoader.load();

Example: Fetch an image, JSON, sound and font together

```js
import { AssetLoader } from "./build/vanilla.js";

const assetLoader = new AssetLoader();
assetLoader.setConcurrency(4);
const imageAsset = assetLoader.addImage("examples/assets/spritesheet.png");
const jsonAsset = assetLoader.addJson("examples/timelineshowcase/assets/combo.timeline.json");
const audioAsset = assetLoader.addAudio("examples/assets/beep.wav");
const fontAsset = assetLoader.addFont("DOSGothic", "examples/assets/DOSGothic.woff");
assetLoader.setProgressHandler((progress, finishedCount, totalCount) => {
	console.log(progress, finishedCount, totalCount);
});
const failedList = await assetLoader.load();
console.log(failedList.length, imageAsset.isLoaded(), jsonAsset.isLoaded(), audioAsset.getDuration(), fontAsset.family);
```

- `constructor()` (constructor, since 0.4.0): Constructor.
- `setConcurrency(concurrency)` (method, since 0.4.0): Sets the number of concurrent loads. (1 or more, fractions are discarded. If changed while loading, applies from the next load)
  - `concurrency` number: Number fetched at the same time. (ignored if not a finite number)
- `getConcurrency()` (method, since 0.4.0): Returns the number of concurrent loads.
  - returns number: Number fetched at the same time. (default 6)
- `addImage(path)` (method, since 0.4.0): Adds an image.
  - `path` string: Image file path.
  - returns ImageAsset: The added image asset. (loaded once load finishes)
- `addJson(path)` (method, since 0.4.0): Adds JSON.
  - `path` string: JSON file path.
  - returns JsonAsset: The added JSON asset.
- `addText(path)` (method, since 0.4.0): Adds text.
  - `path` string: Text file path.
  - returns TextAsset: The added text asset.
- `addBlob(path)` (method, since 0.4.0): Adds binary.
  - `path` string: File path.
  - returns BlobAsset: The added blob asset.
- `addAudio(path)` (method, since 0.4.0): Adds a sound. (Counted as failed in browsers without AudioContext)
  - `path` string: Sound file path.
  - returns AudioAsset: The added sound asset.
- `addFont(family, path, descriptors)` (method, since 0.4.0): Adds a font. (Once loaded, it is registered in document.fonts under the family name, FontAsset.loadFont)
  - `family` string: Font family name to register.
  - `path` string: Font file path.
  - `descriptors` object: FontFace descriptors. (weight, style, etc, omitted if none)
  - returns FontAsset: The added font asset.
- `addAsset(asset, path)` (method, since 0.4.0): Adds an asset. (An Asset subclass loaded with asset.load(path), counted as failed if isLoaded() is false after loading)
  - `asset` object: An asset fetched with asset.load(path).
  - `path` string: Path to fetch.
  - returns object: The added asset.
- `addTask(path, loadFunction)` (method, since 0.4.0): Adds a custom load. (loadFunction is a function that returns a Promise, counted as failed if it throws)
  - `path` string: Name shown in the failed list and progress.
  - `loadFunction` () => Promise<any>: Load function. (returns a Promise, counted as a failure if it rejects)

  Example: Fetch something that is not an asset together

  ```js
  import { AssetLoader } from "./build/vanilla.js";
  
  const assetLoader = new AssetLoader();
  const timelineList = [];
  assetLoader.addTask("logo.timeline.json", async () => {
  	const response = await fetch("examples/timelineshowcase/assets/logo.timeline.json");
  	const timeline = await response.json();
  	timelineList.push(timeline);
  });
  assetLoader.setCompleteHandler((failedList) => {
  	console.log(failedList.length, timelineList.length);
  });
  await assetLoader.load();
  ```

- `addEntry(path, loadFunction, asset)` (method, since 0.4.0): Adds to the list.
  - `path` string: Name shown in the failed list and progress.
  - `loadFunction` () => Promise<any>: Load function. (returns a Promise)
  - `asset` object | null: Asset whose isLoaded() confirms success after loading. (not checked if null)
- `load()` (method, since 0.4.0): Loads. (Waits until everything added is loaded. Does not throw on failure and returns the failed list)
  - returns Promise<Array<{ path: string, error: any }>>: A promise resolved with the failure list when everything is done. (an empty array if nothing failed, the same promise if called again while loading)
- `async runWorkers()` (method, since 0.4.0): Runs the loading workers. (As many workers as the concurrency pick up and load the next item in the list)
  - returns Promise<Array<object>>: A promise resolved with the failure list when everything is done.
- `startWorkers()` (method, since 0.4.0): Launches workers. (If fewer workers are running than the concurrency, launches more, as many as the items nobody has picked up yet)
- `async runWorker()` (method, since 0.4.0): One worker. (Picks up and loads items one by one until the list is empty)
  - returns Promise<void>: A promise resolved when the list is empty.
- `notifyProgress()` (method, since 0.4.0): Notifies progress.
- `setProgressHandler(progressHandler)` (method, since 0.4.0): Sets the progress handler function. ((progress, finishedCount, totalCount) => void, null turns it off)
  - `progressHandler` ((progress: number, finishedCount: number, totalCount: number) => void) | null: Function that receives the progress (0 ~ 1), finished count and total count whenever progress changes. (off if null)
- `setCompleteHandler(completeHandler)` (method, since 0.4.0): Sets the completion handler function. ((failedList) => void, null turns it off)
  - `completeHandler` ((failedList: Array<object>) => void) | null: Function that receives the failure list when everything is done. (off if null)
- `getProgress()` (method, since 0.4.0): Progress. (Finished count / total count, 1 if nothing was added)
  - returns number: 0 ~ 1
- `getTotalCount()` (method, since 0.4.0): Total count.
  - returns number: Added count.
- `getFinishedCount()` (method, since 0.4.0): Finished count. (Loaded and failed)
  - returns number: Finished count.
- `getLoadedCount()` (method, since 0.4.0): Loaded count. (Excluding failed)
  - returns number: Loaded count.
- `getFailedList()` (method, since 0.4.0): Failed list. (Copy of { path, error })
  - returns Array<{ path: string, error: any }>: A copy of the failure list.
- `getInFlightCount()` (method, since 0.4.0): Number currently loading. (Picked up by a worker and not yet finished)
  - returns number: Count being fetched.
- `isFinished()` (method, since 0.4.0): Whether everything added has been loaded. (Including failures, true if nothing was added)
  - returns boolean: True if everything is finished.
