prejs
v1.2.6
Published
A lightweight preloading javascript library for images, video and audio without any dependencies.
Downloads
5
Maintainers
Readme
Introduction
PreJS is a lightweight preloading javascript library for images, video and audio without any dependencies.
Installation
Using npm
$ npm install prejs --save
Using Yarn
$ yarn add prejs
Usage
import PreJS from 'prejs'
let $progress = document.querySelector('.progress')
let pre = new PreJS()
let images = [
'http://i.imgur.com/Wo0Kyth.jpg',
'http://i.imgur.com/5pKVfC1.jpg',
'http://i.imgur.com/1yK4wnx.gif',
'http://i.imgur.com/GsBSYth.mp4',
'http://i.imgur.com/YUxVkvN.png',
'http://i.imgur.com/68Tnk5j.jpg',
]
pre.on('start', () => {
console.log('Starting')
})
pre.on('progress', progress => {
$progress.style.width = progress * 100 + '%'
})
pre.load(images)
Events
'start'
Fired when the loader attempts to load the first item.
'loaded'
Fired when an individual item is finished loading in, use this if you want a progressive indiciation of items loading. Returns: item
'error'
Fired when an individual item is fails to load, you can use this to handle image fallbacks. Returns: item
'progress'
Fired when the overall loader progress increases (due to an item loading/partially loading). Returns: progress (number between 0 - 1)
'complete'
Fired when all items have either loaded or errored out. Returns array of items
Item
| key | value | description | | --- | --- | --- | | url | string | The original url given to the loader | | progress | number | A value between 0 - 1 showing the percentage loaded | | asset | HTMLElement | Returns a html element (img, audio, video, etc..), this can be modified and appended to the page |
API
load(urls, loader)
Accepts an array of urls and a loader type to handle them.
Built in loaders are:
'image'
Loads .jpg, .png, .svg, .jpeg and anything else Image() accepts. Uses the Image() element to load in files.
'audio'
Loads .mp3, .ogg, .wave and anything else Audio() accepts. Uses the Audio() element to load in files.
'video'
Loads .mp4, .ogv, .webm files. Uses XMLHttpRequest to grab the full video, this unfortunately means that its IE10+ and restricted to same origin unless the host has the correct Cross-Origin headers set.
If a loader is not defined explicitly, PreJS will attempt to figure out which loader to use based on the file extension.
// loader can be a string:
pre.load([url1, url2, url3], 'image')
// loader can be undefined and PreJS will guess:
pre.load([url1, url2, url3])
// or your own function:
pre.load([url1, url2, url3], (item) => {
console.log(item)
customLoadingFunction(() => {
pre.loaded(item)
})
})
on(event, cb)
Add an event listener to different events.
pre.on('loaded', (item) => {
console.log('loaded:', item)
})
dispatch(event)
Dispatch all event listeners for an event.
pre.dispatch('loaded', item)