1.2.0 • Published 4 years ago

simple-resource-preloader v1.2.0

Weekly downloads
5
License
MIT
Repository
github
Last release
4 years ago

Simple Resources Preloader

Load any resources using vanilla JS (ES6) with triggering events and/or callbacks.
It uses ES6 class syntax, you can check browser support here. If you need IE support you need to transpile code to ES5 with Babel or other transpiler or use converted code to ES5 version.

  1. Installation
  2. Basic Usage
  3. Options
  4. Events
  5. Methods and Properties
  6. Without bundler usage
  7. ES5 Usage
  8. License

Installation

npm install simple-resources-preloader

Basic Usage

If you are using Webpack or another bundler you can just import it. If you don't use any bundlers go to this section .

import SRPreloader from 'simple-resources-preloader';

Then you need to create a new preloader object, only "files" is required property, but you can set it later with setter "preloader.files".

const preloader = new SRPreloader({
    files: ['./video/intro.mp4', './video/background.mp4']
});

to execute preloader you need to run .preload() method

preloader.preload();

You can use styleVar option value in css code

.preloader::before {
    transition: width 0.1s;
    width:var(--preloader-progress);
}

Options

KeyDefault valueExamples of other valuesTypeDescription
callbackhide preloader functionfunction(a, b){}function\anyThis function will run after preload complete without errors1
cbParams[][1, 'any string', true]arrayArray of parameters for function stored in callback key
debugfalsetrue\'true'boolean\stringYou can enable additional messages in console2
eventEnd'preloadend''anyString'stringEvent name that will be triggered on end of preloading
eventError'preloaderror''anyString'stringEvent name that will be triggered on errors
eventProgress'preloadprogress''anyString'stringEvent name that will be triggered on progress changes
eventstruefalse\'true'boolean\stringYou can disable all events triggering with the plugin2
eventsTargetdocument'#selector'\DOMstring\DOM objectAll events will trigger on this DOM element or document3
files[]['path\file', 'file2']array of stingsFiles list to preload
ifErrorhide preloader functione => console.log(e)function\anyThis function will run after preload complete with errors1
ifErrorParams[][1, 'any string', true]arrayArray of parameters for function stored in ifError key4
onProgressupdate percents functione => console.log(e)function\anythis function will be executed on every percents change1
onProgressParams[][1, 'any string', true]arrayArray of parameters for function stored in onProgress key5
preloaderDOM '#preloader''#selector'\DOMstring\DOM objectHide this DOM element after preload with default functions3
progressNodeList '#preloader [progress]''.selector'\node liststring\NodeList objectThis DOM elements will receive updates of progress attribute6
writePercentsAttr'txt-progress''attribute-name''string'Progress elements with this attribute will get updates of text7
styleVar'--preloader-progress''--variable-name''string'Progress elements will get update of this css variable with percentage value
speedTimeout500'1000'number\stringHow often speed calculation must be updated (value in ms)

All plugin events have event.detail.loaded and event.detail.failed properties, types is number.

preloadend

document.addEventListener('preloadend', e => {
    console.log('total loaded =' + e.detail.loaded); 
    console.log('total fails =' + e.detail.failed); 
});

preloaderror

Error event have event.detail.error property, which contains last Error object.

document.addEventListener('preloaderror', e => {
    console.log(e.detail.error); 
});

preloadprogress

Progress event contains percentage value of loaded files and current speed values

document.addEventListener('preloadprogress', e => {
    console.log(`Loaded ${e.detail.value}%`);
    console.log(`Preload speed is ${e.detail.speed.bytesSpeed} bytes/second`);  
    console.log(`Preload speed is ${e.detail.speed.value} ${e.detail.speed.units}`);
});

Methods and Properties

Start preloader

preloader.preload();

Triggering custom event on target with additional details

Acceptable properties eventName type is string, details type is object

const
    eventName = 'customEvent', 
    details = {
        number:1
    };
preloader.triggerEvent(eventName, details); 

Hiding DOM element stored in preloader.

preloader.hidePreloader();

Show DOM element stored in preloader if it was hidden with 'hidePreloader()'.

preloader.showPreloader();

Update progress elements stored in progress.

preloader.updateProgress();

Getters and setters

Set and get options parameters.

See options section for details.

const defaultOptions = preloader.defaultOptions; //Get options object used by default

preloader.files = ['path/to/file1.ext', 'path/to/file2.ext'];
const filesList = preloader.files;

preloader.preloader = '#preloaderSelector'; 
const preloaderElement = preloader.preloader; //Get DOM element even if selector string stored to options  

preloader.progress = '#progressSelector'; 
const progressElement = preloader.progress; //Get DOM element even if selector string stored to options

preloader.writePercentsAttr = 'attribute';
const progressAttrTxt = preloader.writePercentsAttr; 

preloader.styleVar = '--variable-name';
const styleVar = preloader.styleVar;

preloader.speedTimeout = '250';
const speedTimeout = preloader.speedTimeout; //Get number value even if string is stored to options, if value is invalid returns default value
// main callback
preloader.cbParams = [1, 'a'];
const cbParams = preloader.cbParams;
    
preloader.callback = (a, b) => {
    console.log(a); //expected output – 1 
    console.log(b); //expected output – 'a'
};
const callback = preloader.callback; 
//error callback
preloader.ifErrorParams = [1, 'a'];
const ifErrorParams = preloader.ifErrorParams;
    
preloader.ifError = (error, a, b) => {
    console.log(error); //expected output – Error object
    console.log(a);     //expected output – 1 
    console.log(b);     //expected output – 'a'
};
const ifError = preloader.ifError; 
//percents changing callback
preloader.onProgressParams = [1, 'a'];
const onProgressParams = preloader.onProgressParams;
    
preloader.onProgress = (progress, a, b) => {
    console.log(progress);  //expected output – integer number from 0 to 100
    console.log(a);         //expected output – 1 
    console.log(b);         //expected output – 'a'
};
const onProgress = preloader.onProgress; 

Properties

preloader.error - Last error object

preloader.fileSizes - Array of sile sizes and loaded status

preloader.loaded - Number of successfully loaded files

preloader.noAccess - Number of loading failed files

preloader.options - Object contains current options

preloader.percents - Number from 0 to 100 loaded progress

Without bundler usage

If you want to use it as separate file without any bundler you need to copy 'SimpleResourcePreloader.js' or 'SimpleResourcePreloader.min.js' to your project folder and add type="module" attribute to your script file.
Be careful some browsers still can't import files, so you still need a bundler or transpiler to support those browsers or use ES5 version.

<script type="module" src="./js/script.js"></script>

To import it you can use code like this in you script

import SRPreloader from './lib/SimpleResourcePreloader.min.js';

To init preloader you need to create new object

const preloader = new SRPreloader({
    files: ['./video/intro.mp4', './video/background.mp4']
});

to execute preloader you need to run .preload() method

preloader.preload();

Go back to options section


ES5 Usage

You need to connect plugin script 'SimpleResourcePreloader.es5.js' or 'SimpleResourcePreloader.es5.min.js' before your main script

<!--script src="./js/SimpleResourcePreloader.es5.js"></script-->
<!-- or minified version -->
<script src="./js/SimpleResourcePreloader.es5.min.js"></script>
<script src="./js/script.js"></script>

To init preloader you need to create new object

var preloader = new SimpleResourcePreloader({
    files: ['./video/intro.mp4', './video/background.mp4']
});

to execute preloader you need to run .preload() method

preloader.preload();

Go back to options section


License

MIT