/
.eleventy.js
199 lines (160 loc) · 4.68 KB
/
.eleventy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
const fs = require('fs');
const { JSDOM } = require('jsdom');
const Jimp = require('jimp');
const transformImgPath = (src) => {
if (src.startsWith('/') && !src.startsWith('//')) {
return `.${src}`;
}
return src;
};
const defaultLazyImagesConfig = {
maxPlaceholderWidth: 12,
maxPlaceholderHeight: 12,
placeholderQuality: 60,
imgSelector: 'img',
transformImgPath,
className: 'lazyload',
cacheFile: '.lazyimages.json',
appendInitScript: true,
scriptSrc: 'https://cdn.jsdelivr.net/npm/lazysizes@5/lazysizes.min.js',
};
let lazyImagesConfig = defaultLazyImagesConfig;
let lazyImagesCache = {};
const logMessage = (message) => {
console.log(`LazyImages - ${message}`);
};
const loadCache = () => {
const { cacheFile } = lazyImagesConfig;
if (!cacheFile) {
return;
}
try {
if (fs.existsSync(cacheFile)) {
const cachedData = fs.readFileSync(cacheFile, 'utf8');
lazyImagesCache = JSON.parse(cachedData);
}
} catch(e) {
console.error('LazyImages: cacheFile', e);
}
};
const readCache = (imageSrc) => {
if (imageSrc in lazyImagesCache) {
return lazyImagesCache[imageSrc];
}
return undefined;
};
const updateCache = (imageSrc, imageData) => {
const { cacheFile } = lazyImagesConfig;
lazyImagesCache[imageSrc] = imageData;
if (cacheFile) {
const cacheData = JSON.stringify(lazyImagesCache);
fs.writeFile(cacheFile, cacheData, (err) => {
if (err) {
console.error('LazyImages: cacheFile', e);
}
});
}
};
const getImageData = async imageSrc => {
const {
maxPlaceholderWidth,
maxPlaceholderHeight,
placeholderQuality,
} = lazyImagesConfig;
let imageData = readCache(imageSrc);
if (imageData) {
return imageData;
}
logMessage(`started processing ${imageSrc}`);
const image = await Jimp.read(imageSrc);
const width = image.bitmap.width;
const height = image.bitmap.height;
const resized = image
.scaleToFit(maxPlaceholderWidth, maxPlaceholderHeight)
.quality(placeholderQuality);
const encoded = await resized.getBase64Async(Jimp.MIME_JPEG);
imageData = {
width,
height,
src: encoded,
};
logMessage(`finished processing ${imageSrc}`);
updateCache(imageSrc, imageData);
return imageData;
};
const processImage = async imgElem => {
const { transformImgPath, className } = lazyImagesConfig;
const imgPath = transformImgPath(imgElem.src);
imgElem.setAttribute('loading', 'lazy');
imgElem.setAttribute('data-src', imgElem.src);
imgElem.classList.add(className);
if (imgElem.hasAttribute('srcset')) {
const srcSet = imgElem.getAttribute('srcset');
imgElem.setAttribute('data-srcset', srcSet);
imgElem.removeAttribute('srcset');
}
try {
const image = await getImageData(imgPath);
imgElem.setAttribute('width', image.width);
imgElem.setAttribute('height', image.height);
imgElem.setAttribute('src', image.src);
} catch (e) {
console.error('LazyImages', imgPath, e);
}
};
// Have to use lowest common denominator JS language features here
// because we don't know what the target browser support is
const initLazyImages = function(selector, src) {
if ('loading' in HTMLImageElement.prototype) {
var images = document.querySelectorAll(selector);
var numImages = images.length;
if (numImages > 0) {
for (var i = 0; i < numImages; i++) {
images[i].src = images[i].dataset.src;
}
}
return;
}
var script = document.createElement('script');
script.async = true;
script.src = src;
document.body.appendChild(script);
};
const transformMarkup = async (rawContent, outputPath) => {
const { imgSelector, appendInitScript, scriptSrc } = lazyImagesConfig;
let content = rawContent;
if (outputPath.endsWith('.html')) {
const dom = new JSDOM(content);
const images = [...dom.window.document.querySelectorAll(imgSelector)];
if (images.length > 0) {
logMessage(`found ${images.length} images in ${outputPath}`);
await Promise.all(images.map(processImage));
logMessage(`processed ${images.length} images in ${outputPath}`);
if (appendInitScript) {
dom.window.document.body.insertAdjacentHTML(
'beforeend',
`<script>
(${initLazyImages.toString()})(
'${imgSelector}',
'${scriptSrc}'
);
</script>`
);
}
content = dom.serialize();
}
}
return content;
};
module.exports = {
initArguments: {},
configFunction: (eleventyConfig, pluginOptions = {}) => {
lazyImagesConfig = Object.assign(
{},
defaultLazyImagesConfig,
pluginOptions
);
loadCache();
eleventyConfig.addTransform('lazyimages', transformMarkup);
},
};