Asynchronous Media Preloading for Faster Webpages – ImgPreload.js

Category: Javascript , Loading | December 25, 2023
Author:YuketsuSh
Views Total:42 views
Official Page:Go to website
Last Update:December 25, 2023
License:MIT

Preview:

Asynchronous Media Preloading for Faster Webpages – ImgPreload.js

Description:

Images, audio, and video often represent large files that can delay page load if not handled efficiently.

ImgPreload.js is a tiny yet robust JavaScript library that can reduce load times by preloading and displaying rich media content asynchronously, resulting in a smoother and more enjoyable user experience.

How to use it:

1. Download and load the ImgPreload.js script in the document.

<script src="ImgPreload.js"></script>
2. Preload and display images/videos/audios tagged with the data-src attribute, and manage background images via data-background:
<img data-src="example.jpg" alt="Example Image">
<video controls data-src="example.mp4"></video>
<audio controls data-src="example.mp3"></audio>
<div data-background="bg.png"></div>
document.addEventListener('DOMContentLoaded', async function() {
  try {
    await window.ImgPreload.preloadAndShowImages();
    console.log('Loaded');
  } catch (error) {
    console.error('Error:', error);
  }
  try {
    await window.ImgPreload.preloadAndShowMedia();
    console.log('Loaded & Displayed');
  } catch (error){
    console.error('Error:', error)
  }
});

3. Set the file preloading priority using the data-preload-priority attribute:

<img data-src="example.jpg" data-preload-priority="4" alt="Example Image">
<video controls data-src="example.mp4" data-preload-priority="3"></video>
<audio controls data-src="example.mp3" data-preload-priority="2"></audio>
<div data-background="bg.png" data-preload-priority="1"></div>

4. The library also allows for advanced resource management, offering methods to set memory thresholds, cache sizes, cache durations, and cache cleaning intervals.

// The memory threshold
window.ImgPreload.setPreloadMemory(quantity);
// The maximum cache size
window.ImgPreload.setPreloadCacheSize(size);
// The cache duration in milliseconds
window.ImgPreload.setCacheDuration(durationInMilliseconds);
// The interval duration in milliseconds for cleaning the cache
window.ImgPreload.setCacheCleanInterval(intervalInMilliseconds);

You Might Be Interested In:


Leave a Reply