-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathhelpers.js
81 lines (69 loc) · 2.32 KB
/
helpers.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
const path = require('path');
// Ensures relative paths start in the project root
exports.transformImgPath = (src, options = {}) => {
if (
src.startsWith('./') ||
src.startsWith('../') ||
(!src.startsWith('/') &&
!src.startsWith('http://') &&
!src.startsWith('https://') &&
!src.startsWith('data:'))
) {
// The file path is relative to the output document
const outputDir = path.posix.parse(options.inputPath).dir;
return path.posix.normalize(outputDir + '/' + src);
}
// Reference files from the root project directory
if (src.startsWith('/') && !src.startsWith('//')) {
return `.${src}`;
}
return src;
};
// Logs a message prepended with "LazyImages - "
exports.logMessage = (message) => {
console.log(`LazyImages - ${message}`);
};
// Init script for the plugin that gets injected into the final markup
// (we have to use lowest common denominator JS language features
// because we don't know what the target browser support is)
exports.initScript = function (selector, src, preferNativeLazyLoad) {
var images = document.querySelectorAll(selector);
var numImages = images.length;
if (numImages > 0) {
if (preferNativeLazyLoad && 'loading' in HTMLImageElement.prototype) {
for (var i = 0; i < numImages; i++) {
var keys = ['src', 'srcset'];
for (var j = 0; j < keys.length; j++) {
if (images[i].hasAttribute('data-' + keys[j])) {
var value = images[i].getAttribute('data-' + keys[j]);
images[i].setAttribute(keys[j], value);
}
}
}
return;
}
var script = document.createElement('script');
script.async = true;
script.src = src;
document.body.appendChild(script);
}
};
// Warns about common issues with custom configs
exports.checkConfig = (config, defaultConfig) => {
const { appendInitScript, className } = config;
const isDefaultScriptSrc = config.scriptSrc === defaultConfig.scriptSrc;
if (!isDefaultScriptSrc && !appendInitScript) {
console.warn(
'LazyImages - scriptSrc will be ignored because appendInitScript=false'
);
}
if (
isDefaultScriptSrc &&
appendInitScript &&
!className.includes('lazyload')
) {
console.warn(
'LazyImages - LazySizes with the default config requires "lazyload" be included in className'
);
}
};