<commit_before>---
title: Lazy Load
layout: page.jade
sidebar: true
collection: js
priority: 0
path: lazy-load
---

# Lazy Load
<p class="lead">Lazy Load is a component responsible to handle delayed image rendering, to prevent unnecessary requests to never used images.</p>

## How to use
The Lazy Load component works a bit differently than most Lazy Load plugins out there. Instead of providing something like `<img data-src="src/img" />` (which is not a good call, since a few browsers will try to fetch even without the `src`, forcing 404 on the image).

Instead of it, this plugin work with placeholders:

```html
  <div data-lazy data-src="src/img.png"></div>
  <noscript>
    <img src="src/img.png"/>
  </noscript>

  /* This way the tell search engines we have an image there */
```

You can also work with a `data-srcset`, which will select the image the best image based on window width:

```html
<div data-lazy data-srcset="src/mobile.png 0, src/tablet.png 768, src/desktop.png 1024"></div>
/* The plugin will loop through, and try to match the closest image based on the current window width. */

/* Supposing the window width is 800px, the result would be: */

<img src="src/tablet.png" />
```

The plugin will loop through all attributes of the placeholder, ignoring the plugin ones, such as `[data-src]`, `[data-srcset]` or the selector, which by default is `[data-lazy]` in order to place them again to the final img:

```html
<div data-lazy data-src="src/img.png" class="image" data-image="true"></div>

/* Will result: */
<img src="src/img.png" class="image" data-image="true" />
```

Please take note the placeholder will not carry on binded JavaScript actions to it. Such as eventListeners.

## Initializing

You can use as a jQuery plugin:

```js
$('[data-lazy]').lazyload(options);
```

Or as a vanilla constructor:

```js
import LazyLoad from 'src/js/components/lazy-load';

let lazyLoad = new LazyLoad(document.querySelectorAll('[data-lazy]')).init();
```

The provided options are:

```js
// defaults
let options {
  throttle: 1000, // the throttle delay (ms) to prevent multiple calls
  offset: 200, // the offset (px) to load images. Set to 0 to load the image only when it is visible.
  selector: '[data-lazy]' // the provided selector to query. If you change the selector to something else, pass it here to avoid passing it to the created image.
};
```<commit_msg>docs(form-validation): update lazy docs<commit_after>---
title: Lazy Load
layout: page.jade
sidebar: true
collection: js
priority: 0
path: lazy-load
---

# Lazy Load
<p class="lead">Lazy Load is a component responsible to handle delayed image rendering, to prevent unnecessary requests to never used images.</p>

## How it works
Usually you will implement lazy load on a page with lots of images, where the user does not necessarily loads them all. This technique to <b>lazy</b> load the pictures you do not want as first load, it's actually pretty easy to implement using our component.

If you want to provide a placeholder or a lower resolution image, you can simply use an `<img />` for it:

```html
  <img data-lazy data-src="src/imageToBeLoaded.png" src="placeholderImage.png"/>
```

`[data-lazy]` will tell the component it's a lazy image (You can change the selector if you want, we will get to it later), and using `[data-src]` the lazy component will replace the provided tag with an `<img />` using `[data-src]` as `[src]`:

```html
  <img data-lazy data-src="src/imageToBeLoaded.png" src="placeholderImage.png"/>

  /* Becomes */

  <img src="src/imageToBeLoaded.png" />
```

In fact, you can use any type of markup in order to create a lazy image:

```html
  <span data-lazy data-src="src/imageToBeLoaded.png"></span>

  /* Becomes */

  <img src="src/imageToBeLoaded.png" />
```

## Attributes
A lazy tag will carry all of it's attributes, except the ones used by the component, such as the selector provided (by default `[data-lazy]`), `[data-src]` and `[data-srcset]`, which we will get to it soon.

```html
  <span data-lazy data-src="src/imageToBeLoaded.png" class="image" data-component="image"></span>

  /* Becomes */

  <img src="src/imageToBeLoaded.png" class="image" data-component="image" />
```

##### * Please take note that a lazy image will not carry any source of data binded to it, such as events.


## Serving images by breakpoint
The lazy component also handles responsive images by default, using the `[data-srcset]`:

```html
  <img data-lazy src="src/placeholder.png" data-srcset="mobile.png 0, tablet.png 768, desktop.png 1280"/>
```

The `[data-srcset]` attribute accepts a list of images, divided by commas, where the first argument is the image source, and the second the `window min-width`. The `min-width` is retrived with `$(window).width()` at the moment of the placeholder/image render/replace process.

You do not have to provide the list in minWidth order, but it's way easier to read if you do so.

##### * Please take note that this approach only happens during render/replace process. It does not happen when you resize your window.


## Initializing the component with JavaScript
Other than just setting up a plain `<img data-lazy />` tag, you need to initialize the component as well. You can initialize it as a jQuery plugin, or as a vanilla constructor. Take note that even the vanilla constructor relies on jQuery to perform a few operations:

#### Using as a jQuery plugin
```js
$('[data-lazy]').lazyload(options);
```

#### Using as a vanilla constructor
```js
new LazyLoad(document.querySelectorAll('[data-lazy]'), options);
```

### Options
The default options are:

| Option            | Description |
|-------------------|-------------|
| throttle (1000ms)     | The amount of time (in ms) to allow the ``[data-lazy]`` verification to be triggered. This prevent bloating of execution, since it's binded to the `scroll` event of the window. |
| offset (200px)       | The offset (in px) allowed before the image actually reaches the viewport. This is intended to smooth a bit the image renderization/visualization process, since it will trigger a bit early then image reaching the bottom of the view. To remove it, set it to 0. |
| selector (string) | The selector to be removed from the attributes transfer operation. By default it is `[data-lazy]`. If you are willing to use other than this, change it here as well. Any valid jQuery selector is valid here. |

The options object is incremental, so you can change just which options you want:


```js
let options = {
  throttle: 4000 // Increasing the throttle wait time
};

$('[data-lazy]').lazyload(options);

// or with vanilla constructor

new LazyLoad(document.querySelectorAll('[data-lazy]'), options);
```

Changing the default selector:

```js
let options: {
  selector: '.lazy-image'
};

$('.lazy-image').lazyload(options);

// or with vanilla constructor

new LazyLoad(document.querySelectorAll('.lazy-image'), options);
```

### Destroying an instance
By default, when the lazy component does not find any other `[data-lazy]` to be checked, it automatically triggers `off` to the `$(window).scroll` event, but you can do it manually:

```js
$('[data-lazy]').lazyload();

$('[data-lazy]').data('lazy-load').destroy();

// or with vanilla constructor

let lazyLoad = new LazyLoad(document.querySelectorAll('[data-lazy]'));

lazyLoad.destroy();
```
{'fraction_non_alphanumeric': 0.12269021739130435, 'fraction_numerical': 0.005978260869565218, 'mean_word_length': 4.1511546536039186, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4360694', 'n_tokens_mistral': 2230, 'n_tokens_neox': 2118, 'n_words': 961}