• Stars
    star
    285
  • Rank 145,115 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 5 years ago
  • Updated 6 months ago

Reviews

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

Repository Details

😴 gandul! accessible lazy loading images

gandul

gandul! 😴 (accessible-image-lazy-load)

MIT license NPM Version File Size Twitter


Accessible lazy loading images

gandul 😴 is a lightweight (<2Kb) non-dependant javascript module that adds a different approach on lazy loading focusing on accessibility. Most existing options work by either making you drop the src attribute of the image or, making you create a base64 data / low resolution blurred alternative version of the image, or also including the img element into a <noscript> tag. This could be hacky and verbose and the main issue with it is that alters the semantics of the original element.

In order to avoid that, gandul 😴 works by taking a common anchor hyperlink <a> as the data source of the image to be loaded and transforms it into a <img> element. This way you don't lose the reference to the image you want to show and, in case there's no JavaScript, your image will still be accessible by users and crawlers.

Basic Example :

<!-- How your HTML will look like: -->
<a href="http://placekitten.com/320/180" class="gandul">Nice kitten</a>

<!-- What the gandul script will output : -->
<img src="http://placekitten.com/320/180" class="gandul" alt="Nice kitten" />
HTML Input gandul 😴 Output
<a href="http://placekitten.com/320/180" class="gandul">Nice kitten</a> <img src="http://placekitten.com/320/180" class="gandul" alt="Nice kitten" />
Nice kitten Nice kitten

How to use it

1. Download the script

You have multiple options to get gandul 😴 ( gandul.min.js ):

2. Get it working

Write an anchor hyperlink with the reference to your image and set the class gandul on it (<a class="gandul">). then, include and call the script :

<!-- How a gandul image reference looks like -->
<a href="http://placekitten.com/200/200" class="gandul">Nice kitten</a>

<!-- Include and call the script -->
<script src="https://unpkg.com/accessible-image-lazy-load"></script>
<script>gandul();</script>

Image Attributes

gandul 😴 will take all the existing attributes on the <a> element and they will be passed to the newly created <img> with a few peculiarities, as <a> elements don't have srcset, sizes, width... attributes, those will be passed as data attributes. Right below you can see the equivalences table and some examples:

In case you want to apply gandul to a different HTML element than a hyperlink (<a>) the image source will be taken from the data-href attribute

<a> attributes <img> attributes equivalence
Anchor hyperlink inner text. alt
href src
data-href src
data-srcset srcset
data-sizes sizes
data-width width

Fully responsive image example:

<!-- Write your hyperlink HTML as it follows : -->
<a href="http://placekitten.com/800/400"
   data-srcset="http://placekitten.com/320/160 320w,
             http://placekitten.com/480/240 480w,
             http://placekitten.com/800/400 800w"
   data-sizes="(max-width: 320px) 280px, (max-width: 480px) 440px, 800px"
   class="gandul">Nice kitten</a>

<!-- To get a responsive image output like this one: -->
<img src="http://placekitten.com/800/400"
	 srcset="http://placekitten.com/320/160 320w,
             http://placekitten.com/480/240 480w,
             http://placekitten.com/800/400 800w"
     sizes="(max-width: 320px) 280px, (max-width: 480px) 440px, 800px"
     class="gandul"
     alt="Nice kitten" />

Setting just the width attribute of an image :

<!-- What you'll write: -->
<a href="http://placekitten.com/800/400" data-width="800" class="gandul">Nice kitten</a>

<!-- What you'll get : -->
<img src="http://placekitten.com/800/400" width="800" alt="Nice kitten" />

Any other attributes :

Any other attributes will remain as they are, which means that if you already set or you need on the <img> an id or different classes, those will be passed through the gandul 😴 script :

<!-- input -->
<a href="http://placekitten.com/800/400" id="cat" class="nice kitten gandul">Nice kitten</a>

<!-- gandul output -->
<img src="http://placekitten.com/800/400" id="cat" class="nice kitten gandul" alt="Nice kitten" />

Options

Some parameters can be send to the gandul 😴 function:

gandul(target, opts, action);
  • target (@string) : a selector targeting all the elements where you want the script to get executed. It defaults to all anchor hyperlinks with the classname gandul : "a.gandul"
  • opts (@object) : an options object containing the fields used by the IntersectionObserver constructor
    • root : element used as viewport of the target. Default value is the brwoser viewport (null)
    • rootMargin : margin of root element to grow or shrink the intersection. Default value takes an extra 50 pixels above and below the viewport ("50px 0px 50px 0px").
    • threshold : percentage of target visibility to trigger the action. Default is 0.
  • action (@function) : A callback function to be executed when the image finishes loading after the target has intersected the given viewport, it comes with image element itself as first parameter (function(img){ /* console.log(img) */ }). The default action when image loads is to attach to the img element the class named 'gandul-active'.

The following example makes use of some of these options, it will target all hyperlinks with the class gandul-hyperlink, will be activated when 50% of the target element is visible and the function used as callback will change the created image border style as defined below:

gandul('a.gandul-hyperlink', { threshold: .5 }, function(img) {
    img.style.border = 'solid red 10px';
});

Development

# Clone the repo
$ git clone https://github.com/alterebro/accessible-image-lazy-load.git
$ cd accessible-image-lazy-load/

# Install dependencies
$ npm install

# Build (any of the below will do it)
$ npm run build
$ gulp

Gandul. Accessible Image Lazy loading
Jorge Moreno β€” @alterebro

More Repositories

1

css-transform

CSS Transform Playground. Online tool to visualize 2D & 3D CSS3 Transform functions.
HTML
142
star
2

jQuery.NiceFileInput.js

jQuery Plugin which makes file input CSS styling an easy task.
HTML
51
star
3

css-tooltip

πŸ’¬ Only CSS lightweight, minimal and simple tooltips. No dependencies, no javascript, no rubbish, just around ~500 Bytes gzipped
SCSS
45
star
4

text2image

Text to Image Generator. Convert any String into a Gradient Image based on its MD5 hash value. JS / Canvas / PHP
JavaScript
24
star
5

alterebro.github.io

Github User Page JavaScript Generator built with Vue.js that creates a dynamic page based on the existing data and repositories of a given GitHub user.
Less
23
star
6

IPA-Keyboard

IPA Keyboard. International Phonetic Alphabet Symbols Web and Desktop Application built using Vue.js, Gulp and Node-Webkit
JavaScript
19
star
7

WeaselCMS

Lightweight flat file CMS written in PHP
PHP
14
star
8

perlin-noise-3d

3D Perlin Noise
JavaScript
13
star
9

instagpx

InstaGPX - Add GPX activity stats to your photos. A Client side image manipulation WebApp created with Vue, Parcel & Sass.
JavaScript
13
star
10

mendiak

⛰️ Montes Vascos / Euskal Herriko Mendiak / Basque Mountains Landscape Generator with Perlin Noise, SVG and JavaScript
JavaScript
9
star
11

mosquito

Mosquito is a mini flyweight Static Site Generator written in PHP that can also be used as simple CMS, it converts Markdown files into HTML using the folder structure where they are stored as URL router model
PHP
7
star
12

jQuery.TypeWriter.js

Typerwriter Pseudo-Matrix-Like Text Effect jQuery Plugin.
JavaScript
6
star
13

p5.fillGradient

Fill shapes in p5.js with Linear, Radial and Conic Gradients.
JavaScript
5
star
14

instagram-cube

InstaCube. Your Instagram feed in a Cube!
Less
5
star
15

PaceCalculator

Running Pace Calculator. JavaScript / HTML5 simple hybrid mobile web application built with PhoneGap ( http://pacecalculator.moro.es )
CSS
5
star
16

area-top-github-users

Top active GitHub users rank generator script written in Node.js for a given geographical area list ( https://git.io/spain )
CSS
4
star
17

counter-app

This is just a counter web application (PWA) that simply count things, it doesn't do anything else.
Vue
4
star
18

rune.save.js

Export any SVG Element and save it as Image (JPG, PNG, SVG and WebP). It works as standalone script and as a Rune.js Plugin.
JavaScript
4
star
19

cierzo

Local weather hybrid app to display wind conditions and forecast for a specific location (Zaragoza, Spain)
JavaScript
3
star
20

NewsVisualizer

CSS3 and jQuery BBC News Responsive Layout Visualizer. https://news.moro.es
PHP
3
star
21

resume

CV / Resume in HTML and PDF format, both generated from Markdown by Node.JS
CSS
2
star
22

mini-lightbox.js

Automatically exported from code.google.com/p/mini-lightbox
HTML
2
star
23

m.js

Minimalistic 1Kb library to prototype Single Page Applications as fast as lightning
JavaScript
2
star
24

youtube-lazy-load

Proper lazy loading on embedded YouTube Videos
JavaScript
2
star
25

random-distribution

A Random() Distribution Visualizer
JavaScript
2
star
26

chain-timeout

Execute chained setTimeout functions using requestAnimationFrame to improve performance
JavaScript
2
star
27

sol.watch

An offline Sun Clock Web App built using SVG / ES6 / Webpack / Vue.js
HTML
2
star
28

password-generator

Little web tool to create multiple passwords to use on your favourite websites / networks from a given master password of your choice.
JavaScript
2
star
29

bullshit-generator

Codebase for the Bullshit Generator website. JS / Gulp / HTML5 / LESS
JavaScript
1
star
30

auto-resize-custom-select

Auto resize drop-down select elements to match the width of the selected option and customize it with CSS
JavaScript
1
star
31

angular-movies-webapp

Test Single Page Web Application using Angular, TypeScript and Sass
TypeScript
1
star
32

HSV.ColorClock

HSV Color Clock. Color changing clock representing visually time by using the HSV color space.
CSS
1
star
33

beaufort-scale

Translate speed to Beaufort wind force scale in both Node and the Browser
JavaScript
1
star
34

racelist.angular

Sample AngularJS Web Application featuring data display using external JSON file, table sorting, result filtering, responsive layout and detail modal windows based on routing.
CSS
1
star
35

armazon.css

armazon.css is a minimalistic, lightweight and super simple CSS3 Boilerplate Micro Framework built on LESS that will make much easier to kick start the development of your responsive web project. Based on normalize.css and Skeleton.
HTML
1
star
36

instagram-feed

Get the latest pictures from an Instagram user or hashtag without OAuth credentials or access token. This is not using the Instagram API platform or Graph API so it doesn't need you to authenticate, authorise or register your application anywhere.
PHP
1
star
37

10Print.Cubes

10Print Variation. Concave / Convex cube Pattern Generator
JavaScript
1
star
38

window.message

Simple console.log and window.alert message display replacement both implemented as jQuery plugin and plain vanilla JavaScript.
JavaScript
1
star