• Stars
    star
    5,575
  • Rank 7,121 (Top 0.2 %)
  • Language
    JavaScript
  • Created about 9 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A modern lazy loading library for images.

Layzr.js

Layzr.js on NPM Layzr.js Downloads on NPM jsDelivr Hits Standard JavaScript Style

A modern lazy loading library for images.

Getting Started

Follow these steps:

  1. Install
  2. Setup Images
  3. Instantiate
  4. Review Options
  5. Review Events
  6. Review API
  7. Review Example Code
  • Examples progress like a coffee addiction: small -> medium -> large

Install

Layzr was developed with a modern JavaScript workflow in mind. To use it, it's recommended you have a build system in place that can transpile ES6, and bundle modules. For a minimal boilerplate that fulfills those requirements, check out outset.

Install Layzr, and add it to your package.json dependencies.

$ npm install layzr.js --save

Then import it into the file where you'll use it.

import Layzr from 'layzr.js'

Setup Images

Layzr intelligently chooses the best image source available based on an image's data attributes and browser feature detection.

  • In browsers that support srcset, if available, it will be used to determine the source.
  • In browsers that don't, the normal or retina source will be chosen based on the devicePixelRatio and availability.

Note that all attribute names are configurable via the options passed to Layzr. To indicate potential sources, add the following attributes to your images:

Name Required Optional
data-normal ✓
data-retina ✓
data-srcset ✓

data-normal

Put the normal resolution source in the data-normal attribute.

<img data-normal="normal.jpg">

Note that Layzr selects elements using this attribute. Elements without it won't be tracked, and will never load.

data-retina

Add the retina/high resolution source in the data-retina attribute.

<img data-normal="normal.jpg" data-retina="retina.jpg">

data-srcset

Add the source set in the data-srcset attribute. For information on the proper syntax, read the official specification.

<img data-normal="normal.jpg" data-retina="retina.jpg" data-srcset="small.jpg 320w, medium.jpg 768w, large.jpg 1024w">

Instantiate

Create an instance, optionally passing in your options.

Be sure to assign your Layzr instance to a variable. Using your instance, you can:

  • start and stop the event listeners
  • add and remove event handlers
  • accommodate dynamically added elements
// using the default options

const instance = Layzr()

// using custom options

const instance = Layzr({
  // ...
})

Options are explained in the following section.

Options

Default options are shown below, and an explanation of each follows:

const instance = Layzr({
  normal: 'data-normal',
  retina: 'data-retina',
  srcset: 'data-srcset',
  threshold: 0
})

normal

Customize the attribute the normal resolution source is taken from.

const instance = Layzr({
  normal: 'data-normal'
})

retina

Customize the attribute the retina/high resolution source is taken from.

const instance = Layzr({
  retina: 'data-retina'
})

srcset

Customize the attribute the source set is taken from.

const instance = Layzr({
  srcset: 'data-srcset'
})

threshold

Adjust when images load, relative to the viewport. Positive values make images load sooner, negative values make images load later.

Threshold is a percentage of the viewport height, identical to the CSS vh unit.

const instance = Layzr({
  threshold: 0
})

Events

Layzr instances are extended with Knot.js, a browser-based event emitter. Use the event emitter syntax to add and remove handlers. Review the emitter syntax here.

Layzr emits the following events:

src:before

This event is emitted immediately before an image source is set. The image node is passed to the event handler.

instance.on('src:before', (element) => {
  // 'this' is your Layzr instance
  // 'element' is the image node
  // ...
})

Load event handlers should be attached using this event. See the example, and note the caveats associated with image load events before proceeding.

src:after

This event is emitted immediately after an image source is set. The image node is passed to the event handler.

instance.on('src:after', (element) => {
  // 'this' is your Layzr instance
  // 'element' is the image node
  // ...
})

Note that the image is not necessarily done loading when this event fires.

API

All API methods are chainable, including those from the emitter.

.handlers(flag)

Add or remove the scroll and resize event handlers.

instance
  .handlers(true)       // 'true' adds them
  .handlers(false)      // 'false' removes them

.check()

Manually check if elements are in the viewport.

This method is called while the window is scrolled or resized.

instance.check()

.update()

Update the elements Layzr is checking.

instance.update()

Dynamically added elements should be handled using this method. See the example.

Browser Support

Layzr depends on the following browser APIs:

It supports the following natively:

  • Chrome 24+
  • Firefox 23+
  • Safari 6.1+
  • Opera 15+
  • Edge 12+
  • IE 10+
  • iOS Safari 7.1+
  • Android Browser 4.4+

To support older browsers, consider including polyfills/shims for the APIs listed above. There are no plans to include any in the library, in the interest of file size.

Colophon

License

MIT. © 2017 Michael Cavalea

Built With Love

More Repositories

1

bricks.js

A blazing fast masonry layout generator for fixed width elements.
JavaScript
4,657
star
2

jump.js

A modern smooth scrolling library.
JavaScript
3,472
star
3

gotem

Copy to clipboard for modern browsers in less than 1kb.
JavaScript
429
star
4

outset

A minimal frontend boilerplate, emphasizing workflow.
SCSS
170
star
5

knot.js

A browser-based event emitter, for tying things together.
JavaScript
105
star
6

heading-links.js

A small, dependency-free library for deep linking headings - GitHub style.
JavaScript
66
star
7

text-split

Text wrapping for type animations.
JavaScript
46
star
8

nuclear.css

An experiment in generating atomic, immutable, class-based CSS.
CSS
23
star
9

stockpile.js

A tiny localStorage wrapper providing namespacing and typed values.
JavaScript
18
star
10

hsx

Static HTML sites with JSX and webpack (no React).
JavaScript
16
star
11

string-dom

Create HTML strings using JSX (or functions).
JavaScript
13
star
12

maximize.js

A tiny wrapper for cross-browser requestFullscreen.
JavaScript
13
star
13

obzerv

A convenient wrapper around IntersectionObserver for tracking element position relative to the viewport.
JavaScript
11
star
14

string-css

Create CSS-in-JS via tagged template strings.
JavaScript
10
star
15

tail-end

Promise-wrapped CSS animations and transitions (async/await friendly).
HTML
8
star
16

bandito

Boilerplate for mostly-static React frontends.
JavaScript
8
star
17

jax.js

A tiny Promise wrapper for GET requests.
JavaScript
8
star
18

xec

An async script loader, for the browser, built on Promises.
JavaScript
8
star
19

evented-viewport

Viewport width and height utility for JavaScript modules.
JavaScript
7
star
20

ajax-component

A Custom Element that AJAXs its content, style, and scripts.
JavaScript
7
star
21

ique

A queue that runs tasks when the browser is idle.
JavaScript
7
star
22

sublime

My current Sublime Text 3 settings.
6
star
23

next-thing

Frame, tick, and idle functions for the browser.
JavaScript
6
star
24

handmade

DIY build systems, tooling, and more.
JavaScript
6
star
25

selly

Convenient and optimized DOM element selection.
JavaScript
6
star
26

one-ready

A Promise wrapper for DOMContentLoaded that prevents event duplication.
JavaScript
5
star
27

understated

Render stateless components and JSX to real DOM.
JavaScript
5
star
28

outset-lib

A boilerplate for vanilla JavaScript libraries.
JavaScript
5
star
29

dotnot

Access object properties using dot notation.
JavaScript
5
star
30

array-intersect

Array intersection, simplified.
JavaScript
5
star
31

js-trending

GitHub's trending JavaScript repositories as a microservice.
JavaScript
4
star
32

hurry.js

An optimized curry function, for enabling full and partial function application.
JavaScript
3
star
33

outset-react

A boilerplate for React libraries, built with webpack.
JavaScript
3
star
34

reread

Recursively read paths to all files within a folder and its subfolders.
JavaScript
3
star
35

callmecavs.github.io

My personal website.
CSS
3
star
36

handmade-fs

File system tasks for handmade.
JavaScript
2
star
37

ama

You know the drill...
1
star
38

understated-cli

Create understated sites with no configuration.
JavaScript
1
star