Last active
April 8, 2020 22:37
-
-
Save anthonykoch/d7b84adcaa2be2412c14bb2b5de6cdb8 to your computer and use it in GitHub Desktop.
lazyload.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cheerio = require('cheerio'); | |
const genid = require('uuid'); | |
const { URL } = require('url'); | |
const path = require('path'); | |
const compose = (exports.compose = (...functions) => args => | |
functions.reduce((arg, fn) => fn(arg), args)); | |
const dataifyAttributes = ($el, attributes) => { | |
attributes.forEach(attr => { | |
const value = $el.attr(attr); | |
if (value != null) { | |
$el.attr(`data-${attr}`, value); | |
$el.removeAttr(attr); | |
} | |
}); | |
}; | |
/** | |
* @param {Object} options | |
* @param {CheerioStatic} options.$ | |
* @param {Object} options.lazify | |
*/ | |
const transformLazify = (exports.transformLazify = ({ $, ...options }) => { | |
$('picture').each(function() { | |
const $picture = $(this); | |
if ( | |
options.lazify && | |
options.lazify.picture && | |
options.lazify.picture.filter && | |
!options.lazify.picture.filter(null, $picture, $, options) | |
) { | |
return; | |
} | |
$picture.find('source,img').each(function() { | |
const $el = $(this); | |
dataifyAttributes($el, ['src', 'srcset', 'sizes']); | |
}); | |
const imgClassName = $picture.find('img').attr('class') | |
$picture.find('img').attr({ | |
src: | |
'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', | |
class: `${imgClassName || ''} js-lazify is-lazify-picture-img`, | |
}) | |
; | |
}); | |
$('img').each(function() { | |
const $img = $(this); | |
const src = $img.attr('src'); | |
if ($img.attr('data-src')) { | |
return; | |
} | |
if ( | |
options.lazify && | |
options.lazify.img && | |
options.lazify.img.filter && | |
!options.lazify.img.filter(src, $img, $, options) | |
) { | |
return; | |
} | |
dataifyAttributes($img, ['src', 'srcset', 'sizes']); | |
$img.attr({ | |
src: | |
'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', | |
class: $img.attr('class') + ' js-lazify is-lazify-img', | |
}); | |
}); | |
return { | |
...options, | |
$, | |
}; | |
}); | |
/** | |
* @param {string} html | |
*/ | |
const loadHtml = (exports.loadHtml = function loadHtml( | |
html, | |
{ extractBody = true, ...options } = {} | |
) { | |
const $ = cheerio.load(html); | |
return { | |
$, | |
extractBody, | |
...options, | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment