Preload Specified Assets Using XHR2 – preload-it

Category: Javascript , Loading , Recommended | December 2, 2019
Author:andreupifarre
Views Total:83 views
Official Page:Go to website
Last Update:December 2, 2019
License:MIT

Preview:

Preload Specified Assets Using XHR2 – preload-it

Description:

The preload-it library preloads & prefetches assets (e.g. videos, audios, etc) using XMLHttpRequest to optimize the loading speed of your webpage.

Also provides event handlers which will be fired based on the loading status.

How to use it:

Install & Import the preload-it.

# NPM
$ npm install preload-it --save
import preload from 'preload-it';

Or directly load the library from a CDN.

<script src="https://unpkg.com/[email protected]/dist/preload-it.js"></script>

Create a new Preload instance to initialize the library.

const instance = Preload();

Specify an array of resources to prefetch.

instance.fetch([
  '1.mp4',
  '2.mp4',
  '1.jpg'
])

Output the resources that are completely loaded.

instance.fetch([
  '1.mp4',
  '2.mp4',
  '1.jpg'
]).then(items => {
  console.log(items);
});

Or…

instance.oncomplete = items => {
  console.log(items);
}

Output the current loading progress.

instance.onprogress = event => {
  console.log(event.progress + '%');
}

Output the prefetched resources.

instance.onfetched = item => {
  console.log(item);
}

Execute a function when an error occured.

instance.onerror = item => {
  console.log(item);
}

Execute a function on cancel.

instance.oncancel = items => {
  console.log(items);
}

Cancle preloading of assets.

instance.cancel();

Changelog:

v1.4.0 (12/02/2019)

  • added cancel method and oncancel event

v1.3.1 (12/01/2019)

  • added progress computational mode: stepped
  • added error handling

You Might Be Interested In:


Leave a Reply