Lozad.js - Documentation

Introduction

What is Lozad.js?

Lozad.js is a small, fast, and lightweight JavaScript library for lazy loading images. It uses Intersection Observer API to detect when an image is about to enter the viewport and loads it only then. This improves the initial page load time and overall performance, especially on websites with many images. It’s designed to be unobtrusive and easy to integrate into existing projects.

Why use Lozad.js?

Using Lozad.js offers several key advantages:

Key Features

Installation

Lozad.js can be installed using several methods:

After installation, you’ll need to initialize Lozad.js and specify the selectors for the elements you want to lazy load. Refer to the usage section of the documentation for detailed instructions.

Getting Started

Basic Usage

The most basic usage of Lozad.js involves selecting the elements you want to lazy load and then initializing the library. Here’s a minimal example:

const observer = lozad(); // lazy loading elements with default configuration
observer.observe();

This assumes you have already included Lozad.js in your project (see Installation section). This code will find all images with the class lazyload and load them lazily. It uses the default configuration. To utilize this, add the lazyload class to your image tags:

<img class="lazyload" data-src="image.jpg" alt="My Image">

The data-src attribute is crucial; it contains the actual image URL. Lozad.js will replace this attribute with the src attribute once the image is ready to be loaded.

Configuration Options

Lozad.js offers several configuration options to customize its behavior:

These options can be passed as an object to the lozad constructor:

const observer = lozad({
  rootMargin: '100px', // preload images when 100px away
  threshold: 0.5,     // load when 50% of element is visible
  loaded: function(element) {
    element.classList.add('loaded'); // add a custom class for styling purposes
  },
  error: function(element) {
    element.classList.add('error'); // add an error class for styling purposes
  }
});
observer.observe();

Root Element Selection

To improve performance, especially on large pages, you can restrict Lozad.js to observe elements within a specific container. For instance, if you want to lazy load images only inside a container with the ID images-container, you would use the root option:

const observer = lozad({
  root: document.getElementById('images-container')
});
observer.observe();

All elements matching your selector inside #images-container will be lazy loaded.

Loading Placeholder

You might want to display a placeholder while images are loading. This can be achieved using CSS and a placeholder image. Set a background image on your elements:

<img class="lazyload" data-src="image.jpg" alt="My Image" style="background-image: url('placeholder.jpg');">

Ensure that the placeholder image is appropriately sized, and adjust the CSS to handle the transition once the real image loads.

Example: Image Loading

This example demonstrates lazy loading images within a specific container:

<div id="image-container">
  <img class="lazyload" data-src="image1.jpg" alt="Image 1">
  <img class="lazyload" data-src="image2.jpg" alt="Image 2">
  <img class="lazyload" data-src="image3.jpg" alt="Image 3">
</div>

<script>
  const observer = lozad({
    root: document.getElementById('image-container'),
    loaded: function(element) {
      element.classList.add('loaded');
    }
  });
  observer.observe();
</script>

<style>
  .lazyload {
    width: 200px;
    height: 150px;
    background-color: #eee; /* Default placeholder */
  }
  .lazyload.loaded {
    background-color: transparent; /* Remove the background once image loaded*/
  }
</style>

Remember to replace "image1.jpg", "image2.jpg", and "image3.jpg" with the actual paths to your images. This example uses simple CSS for the placeholder; more sophisticated techniques can be used for better visual feedback.

Advanced Usage

Custom Callbacks

Lozad.js allows for extensive customization through callback functions. Beyond the loaded and error callbacks already mentioned, you can create more sophisticated behavior by leveraging these functions:

Example incorporating load and unobserve:

const observer = lozad({
  loaded: function(picture) {
    picture.classList.add('loaded');
  },
  load: function(picture) {
      // Perform pre-loading actions here, e.g., display a spinner
      picture.classList.add('loading');
  },
  unobserve: function(picture) {
    // Clean up after the element is unobserved
    console.log("Element unobserved:", picture);
  }
});
observer.observe();

// Later, if needed, unobserve a specific element:
// const elementToRemove = document.getElementById('myImage');
// observer.unobserve(elementToRemove);

Error Handling

The error callback is crucial for gracefully handling situations where images fail to load. You can use this to display alternative images, error messages, or perform other corrective actions:

const observer = lozad({
  error: function(element) {
    element.src = 'error.jpg'; // Replace with a default error image
    element.classList.add('error');
  }
});
observer.observe();

Lazy Loading for Different Element Types (iframes, videos)

Lozad.js is not limited to images; it works with iframes and videos as well. Simply use the appropriate tag and data-src attribute:

Iframe:

<iframe class="lazyload" data-src="https://example.com/iframe"></iframe>

Video:

<video class="lazyload" poster="poster.jpg" data-src="video.mp4"></video>

Remember to adjust your CSS selectors and potentially add different placeholder styles for different element types.

Using Lozad.js with other libraries

Lozad.js is designed to work well with other JavaScript libraries. There should be no conflicts unless the other libraries interfere with the DOM elements Lozad.js operates on or directly manipulate the Intersection Observer API. However, ensure proper initialization order; Lozad.js should ideally run after other libraries that modify the DOM structure affecting the lazy-loaded elements have finished executing.

Performance Optimization

For optimal performance:

Debugging Tips

API Reference

Lozad Constructor

The Lozad constructor initializes a new lazy loading instance. It accepts a single optional argument: an object containing configuration options (see Configuration Options in the Getting Started section).

const observer = lozad({
  // Configuration options here...
});

If no options are provided, it uses the default settings. The returned observer object is an instance of Lozad and contains methods for controlling the lazy loading process.

observe()

The observe() method starts observing the selected elements. It’s automatically called when you create a new Lozad instance unless autoRender is set to false in the constructor options. You can call it manually if you need to start observation later, for example, after adding new elements to the DOM:

const observer = lozad(); // Or with config options
// ... some DOM manipulation ...
observer.observe();

unobserve()

The unobserve() method stops observing elements. You can use it to stop observing all elements:

observer.unobserve();

Or to stop observing a specific element:

const element = document.getElementById('myElement');
observer.unobserve(element);

This is useful for performance optimization when elements are removed from the DOM or are no longer needed.

trigger()

The trigger() method forces the loading of all observed elements. This is useful in scenarios where you want to load all images immediately, perhaps after a user action like clicking a button:

observer.trigger();

This method bypasses the Intersection Observer and loads all elements regardless of their visibility.

autoUnobserve()

The autoUnobserve() method configures whether Lozad automatically removes elements from observation when they are unmounted from the DOM. This is enabled by default, but can be disabled for specific use cases. The method accepts a boolean argument specifying whether to enable or disable this behavior. You can disable this:

observer.autoUnobserve(false);

This can be useful in specific situations where elements are temporarily removed from the DOM and later re-added.

Settings

The settings property of the Lozad instance allows you to access and modify the current configuration options after the instance has been created. You can read the current settings:

console.log(observer.settings);

And modify the settings:

observer.settings.rootMargin = '200px';

Changes to the settings object after initialization will not automatically trigger an update; you may need to call observe() again after changing settings, especially for settings that impact observation behavior (e.g., root, rootMargin, threshold). Changing certain other settings might only affect newly added elements. Refer to the documentation for specific details on each setting’s behavior.

Troubleshooting

Common Issues and Solutions

This section addresses common problems encountered when using Lozad.js and provides solutions.

Debugging Techniques

Troubleshooting Specific Element Types

Remember to consult the Lozad.js documentation for more detailed information and specific examples related to your situation. If you continue to experience problems, consider providing a minimal reproducible example to help others assist you in resolving the issue.

Contributing

Contributing Guidelines

We welcome contributions to Lozad.js! To contribute, please follow these guidelines:

  1. Fork the repository: Create a fork of the Lozad.js repository on GitHub.

  2. Create a branch: Create a new branch for your changes. Use descriptive branch names that clearly indicate the purpose of your changes (e.g., fix/bug-in-selector, feat/add-new-option).

  3. Make your changes: Make your changes to the codebase. Follow the existing coding style and conventions.

  4. Write tests: Add or update tests to cover your changes. Ensure that all existing tests pass before submitting your pull request. Lozad.js uses Jest for testing.

  5. Document your changes: Update the documentation to reflect your changes.

  6. Commit your changes: Commit your changes with clear and concise commit messages. Follow the conventional commit message format (e.g., fix: resolve issue with selector).

  7. Submit a pull request: Create a pull request on GitHub, clearly describing the changes you’ve made and the rationale behind them.

Code of Conduct

We follow a code of conduct based on the Contributor Covenant. We expect all contributors to be respectful and professional in their interactions. Harassment, discrimination, and abusive behavior will not be tolerated.

Reporting Bugs

When reporting bugs, please provide the following information:

Suggesting Features

When suggesting features, please provide the following information:

We appreciate your contributions and look forward to working with you to improve Lozad.js!