Overview
Callbacks (Optional)
javascript images

MF Lazy Images

This library searches for all <img> elements with the lazy class and loads them when they become visible (via a IntersectionObserver), either through scrolling or window resizing.

When triggered, it sets the 'src' attribute from the 'data-lazy-src' value, causing the image to load.

IMPORTANT: I find this class works well with Windows and non-Apple devices- but ipad in particular encounters freezing as Apple runs single threaded.

IMPORTANT: The <img src='myimage.png' loading='lazy'> seems to be a modern non-javascript alternative.

html
<script defer src='https://methodfish.com/Download/MFLazyImages/files/latest/js/mf-lazy-images.js'>
<link rel='stylesheet preload prefetch' as='style' href='https://methodfish.com/Download/MFLazyImages/files/latest/css/mf-lazy-images.css'>

<img src='images/my-unknown-image-icon.png' data-lazy-src='abc.xxx' class='lazy'>

The presence of the lazy class will automatically:

  1. Set up a global _lazyImages object.
  2. Call initLazyImages() to prepare all .lazy images in the DOM for lazy loading.

The class also preloads a few additional images ahead of those in view.

For dynamically added images (e.g. via AJAX), you can call:if (_lazyImages) _lazyImages.initLazyImages();

You can also call _lazyImages.initLazyImages() to reinitialize if the DOM has been independently adjusted (e.g. through ajax or hiding and showing elements).

To handle resize and scrolling - you need to factor in events, which should bind(_lazyImages):

js
document.querySelector('.help-content').addEventListener('scroll',  _lazyImages.initLazyImages.bind(_lazyImages));

Callbacks (Optional)

To run post-processing on each loaded image, either:

  1. Pass a custom callback to the constructor (e.g. define your own const _lazyImages = new MFLazyImages(myCallbackFunc)), or
  2. Define a global MFLazyImagesCallback(img) function, e.g.
javascript
function MFLazyImagesCallback(img) {
   console.log('MFLazyImagesCallback', img);
}

Also see www.robinosborne.co.uk/2016/05/16/lazy-loading-images-dont-rely-on-javascript/


link Click to view a demo

square

About

License

Latest Release

Version 1.012025-07-08