Skip to content

Instantly share code, notes, and snippets.

@aarongustafson
Last active August 23, 2017 07:37
Show Gist options
  • Save aarongustafson/5e400a570584871ee98b83d7781c83a5 to your computer and use it in GitHub Desktop.
Save aarongustafson/5e400a570584871ee98b83d7781c83a5 to your computer and use it in GitHub Desktop.
// Lazy Load Images
// Assumes WebP versions exist for all images
//
// data-img="A|B|C|D|E"
// A = source url
// B = alt
// C = prepend? (y/n)
// D = insert into (descendent selector)
// E = svg?
//
function lazyImages(){
if ( !( 'querySelectorAll' in document ) ){ return; }
var $els = document.querySelectorAll( '[data-img]' ),
i = $els.length,
$el,
$parent,
$picture = document.createElement('picture'),
$webp = document.createElement('source'),
$svg = $webp.cloneNode(true),
$img = document.createElement('img'),
$ins,
data,
file_path,
file_root,
inserted = false;
$webp.type = 'image/webp';
$svg.type = 'image/svg+xml';
$picture.appendChild($webp);
$picture.appendChild($img);
while ( i-- )
{
$el = $els[i];
data = $el.dataset.img.split('|');
// console.log('data',data);
// Get the root file name
file_path = data[0].substring(0, data[0].lastIndexOf('/') + 1);
data[0] = data[0].substring(data[0].lastIndexOf('/') + 1, data[0].length);
data[0] = data[0].split('.');
file_root = file_path + data[0][0];
data[0] = file_path + data[0].join('.');
// Original Image
$img.src = data[0];
$img.alt = ( data[1] ? data[1] : '' );
// WebP
$webp.srcset = file_root + '.webp';
// console.log('WebP source', $webp.srcset);
// SVG?
if ( data[4] &&
data[4] == 'y' )
{
$picture.insertBefore( $svg, $picture.firstChild );
$svg.srcset = file_root + '.svg';
}
else
{
if ( $svg.parentNode == $picture )
{
$picture.removeChild( $svg );
}
}
// Create the insertion
$ins = $picture.cloneNode(true);
// Get the parent (old or new)
$parent = false;
if ( data[3] != '' )
{
$parent = $el.querySelector( data[3] );
}
if ( ! $parent )
{
$parent = $el;
}
// append or prepend?
if ( data[2] == 'y' )
{
$parent.insertBefore( $ins, $parent.firstChild );
}
else
{
$parent.appendChild( $ins );
}
$el.setAttribute('data-imaged', 'true');
}
}
// On DOM Ready
lazyImages();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment