Lazy Load Images, Backgrounds, and AJAX with query-lazy Plugin

File Size: 13.2 KB
Views Total: 396
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Lazy Load Images, Backgrounds, and AJAX with query-lazy Plugin

query-lazy is a simple jQuery-powered lazy loader that allows you to defer loading images, background images, and external pages until they are scrolled into view. 

This can help optimize page load times and avoid loading unnecessary assets too early. Perfect for image-heavy sites or any content-rich pages that don't need to display all elements at once. 

How to use it:

1. Download and load the query-lazy plugin after jQuery.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/dist/jquery-lazy.min.js"></script>

2. Add the data-lazy-src attribute to images or data-lazy-url to elements where you want to lazy load ajax content. 

<!-- Background Image -->
<div data-lazy-src="bg.jpg">
  Content Here
</div>

<!-- Image -->
<img alt=""
     data-lazy-src="image.webp"
     src="OPTIONAL PLACEHOLDER IMAGE"/>

<!-- External Resource -->
<div data-lazy-url="content.html"></div>

3. Initialize the plugin and it will load those assets only when the user scrolls to them.

$('[data-lazy-src],[data-lazy-url]').lazy({
  // options here
});

4. Don't forget to set a minimum height which helps avoid loading all assets at once.

.lazy-waiting,.lazy-loading {
  display: block;
  visibility: hidden;
  min-height: 300px;
}

5. Available plugin options and callbacks.

$('[data-lazy-src],[data-lazy-url]').lazy({

  // lazy load assets in external resources
  recursive: true,

  // useful classes to handle loading states.
  classStatic: 'lazy',
  classWaiting: 'lazy-waiting',
  classLoading: 'lazy-loading',
  classDone: 'lazy-done',

  // callbacks
  onBeforeLoad(element) {
  },
  onLoad(element) {
  },
  onError(element) {
  },
  onCompleted(element) {
  }
  
});

6. Events.

$('body')
.on('beforeLoad.lazy', '.lazy', function (e) {
  console.log('beforeLoad.lazy');
})

.on('loaded.lazy', '.lazy', function (e, width, height, scrollY, scrollX) {
  console.log('load.lazy');
  console.log(e, width, height, scrollY, scrollX);
});

Changelog:

2023-11-11

  • First release

This awesome jQuery plugin is developed by ThomasDev-de. For more Advanced Usages, please check the demo page or visit the official website.