-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjQuery-cache-images.js
304 lines (253 loc) · 10.4 KB
/
jQuery-cache-images.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
!(function ($) {
$.fn.cacheImages = function (options) {
// Validate options argument
if (typeof options !== 'object' || options === null) {
console.error('FV.cacheImage: Error - Invalid options argument');
return this;
}
const self = this; // Declare self as a constant
// Initialize $.fn.cacheImagesConfig with default values
this.cacheImagesConfig = $.extend({}, $.fn.cacheImages.defaults, options);
// Validate $.fn.cacheImagesConfig object
if (typeof this.cacheImagesConfig !== 'object' || this.cacheImagesConfig === null) {
console.error('FV.cacheImage: Error - Invalid cacheImagesConfig object');
return this;
}
// Validate debug property
if (typeof this.cacheImagesConfig.debug !== 'boolean') {
console.error('FV.cacheImage: Error - Invalid debug property');
return this;
}
this.cacheImagesConfig.encodeOnCanvas =
typeof HTMLCanvasElement !== 'undefined' && this.cacheImagesConfig.encodeOnCanvas;
// Validate forceSave property
this.cacheImagesConfig.forceSave =
typeof this.cacheImagesConfig.forceSave === 'boolean'
? this.cacheImagesConfig.forceSave
: false;
// Validate start property
if (typeof this.cacheImagesConfig.start === 'function') {
this.cacheImagesConfig.start(this);
}
// Validate defaultImage property
if (!$.fn.cacheImages.testOutput(this.cacheImagesConfig.defaultImage, true)) {
this.cacheImagesConfig.defaultSrc = this.cacheImagesConfig.defaultImage;
}
this.each(function (index, element) {
// Validate index and element arguments
if (typeof index !== 'number' || element === null || typeof element !== 'object') {
console.error('FV.cacheImage: Error - Invalid index or element arguments');
return true;
}
$.fn.cacheImages.storageAvailable($(element), index, element, function (index, element) {
const $element = $(element);
let src;
if ($element.prop('tagName') === 'IMG') {
$element.data('cachedImageType', 'src');
src = $element.prop('src') || $element.data('cachedImageSrc');
// Validate src property
if (typeof src !== 'string') {
console.error('FV.cacheImage: Error - Invalid src property');
return true;
}
if (self.cacheImagesConfig.url !== null) {
src = self.cacheImagesConfig.url;
$element.prop('src', '');
}
} else {
$element.data('cachedImageType', 'css');
src =
$element.css('background-image').replace(/"/g, '').replace(/url\(|\)$/gi, '') ||
$element.data('cachedImageSrc');
// Validate src property
if (typeof src !== 'string') {
console.error('FV.cacheImage: Error - Invalid src property');
return true;
}
if (self.cacheImagesConfig.url !== null) {
src = self.cacheImagesConfig.url;
$element.css('background-image', 'url()');
}
}
// Validate src property
if (src === undefined || typeof src !== 'string') {
console.error('FV.cacheImage: Error - Invalid or missing URI to load');
self.cacheImagesConfig.fail.call(this, 'Error - Invalid or missing URI to load');
self.cacheImagesConfig.always.call(this);
return true;
}
// Validate output property
if (src !== undefined && $.fn.cacheImages.testOutput($element.prop('src'), true)) {
console.log('FV.cacheImage: already displaying cached image');
self.cacheImagesConfig.done.call(this);
self.cacheImagesConfig.always.call(this);
return true;
}
const storageKey = `${self.cacheImagesConfig.storagePrefix}:${src}`;
$.fn.cacheImages.get($element, storageKey, function (key, cachedData) {
if (
self.cacheImagesConfig.forceSave === 0 &&
cachedData &&
$.fn.cacheImages.testOutput(cachedData, true)
) {
this.data('cachedImageSrc', src);
if (this.data('cachedImageType') === 'src') {
this.prop('src', cachedData);
} else {
this.css('background-image', `url(${cachedData})`);
}
console.log('FV.cacheImage: Already Encoded');
self.cacheImagesConfig.done.call(this, cachedData);
self.cacheImagesConfig.always.call(this);
} else if (cachedData === 'pending') {
console.log(`FV.cacheImage: Caching in Progress - ${src}`);
self.cacheImagesConfig.fail.call(this, 'Caching in Progress');
self.cacheImagesConfig.always.call(this);
} else {
if (this.data('cachedImageType') === 'src') {
this.prop('src', '');
} else {
this.css('background-image', 'url()');
}
const imageTypeMatch = src.match(/\.(jpg|jpeg|png|gif)$/i);
let imageType;
if (imageTypeMatch && imageTypeMatch.length) {
imageType =
imageTypeMatch[1].toLowerCase() === 'jpg' ? 'jpeg' : imageTypeMatch[1].toLowerCase();
}
// Validate imageType property
if (imageType === undefined || typeof imageType !== 'string') {
console.error('FV.cacheImage: Error - Unable to determine valid image type');
self.cacheImagesConfig.fail.call(this, 'Error - Unable to determine valid image type');
self.cacheImagesConfig.always.call(this);
return;
}
this.data('cachedImageSrc', src);
$.fn.cacheImages.set(this, storageKey, 'pending', function (key, data) {});
if (self.cacheImagesConfig.encodeOnCanvas && imageType !== 'gif') {
console.log(`FV.cacheImage: Preparing to Cache : canvas - ${src}`);
$element.on('load', function () {
const newSrc = $.fn.cacheImages.base64EncodeCanvas(this, imageType);
$.fn.cacheImages.set(this, storageKey, newSrc);
if ($.fn.cacheImages.testOutput(newSrc, true)) {
if (this.data('cachedImageType') === 'src') {
this.prop('src', newSrc);
} else {
this.css('background-image', `url(${newSrc})`);
}
if (this.is('.cacheImagesRemove')) {
this.remove();
}
self.cacheImagesConfig.done.call(this, newSrc);
} else {
self.cacheImagesConfig.fail.call(this, 'Error - Unable to encode on canvas');
}
self.cacheImagesConfig.always.call(this);
// Unbind the load event handler to prevent potential memory leaks
$element.off('load');
});
} else {
console.log(`FV.cacheImage: Preparing to Cache : base64 - ${src}`);
$.fn.cacheImages.base64EncodeImg(this, function (newSrc) {
$.fn.cacheImages.set(this, storageKey, newSrc, function () {
if (this.is('.cacheImagesRemove')) {
this.remove();
}
if (this.data('cachedImageType') === 'src') {
this.prop('src', newSrc);
} else {
this.css('background-image', `url(${newSrc})`);
}
self.cacheImagesConfig.done.call(this, newSrc);
self.cacheImagesConfig.always.call(this);
});
});
}
}
});
});
});
return this;
};
$.fn.cacheImages.defaults = {
storagePrefix: 'FV-cacheImage',
url: null,
forceSave: false,
defaultImage: null,
encodeOnCanvas: false,
done: function () {},
fail: function () {},
always: function () {},
start: function () {},
debug: false,
};
$.fn.cacheImages.storageAvailable = function ($element, index, element, callback) {
// Validate $element argument
if (!($element instanceof $) || $element.length === 0) {
console.error('FV.cacheImage: Error - Invalid $element argument');
return false;
}
callback(index, element);
};
$.fn.cacheImages.base64EncodeImg = function (element, callback) {
const image = new Image();
image.onload = function () {
const canvas = document.createElement('CANVAS');
const context = canvas.getContext('2d');
canvas.height = image.height;
canvas.width = image.width;
context.drawImage(image, 0, 0);
callback(canvas.toDataURL('image/png'));
};
// Add error handling for image loading
image.onerror = function () {
callback(null, 'Error - unable to load image');
};
// Validate element.src property
if (typeof element.src !== 'string') {
console.error('FV.cacheImage: Error - Invalid element.src property');
return;
}
image.src = element.src;
};
$.fn.cacheImages.base64EncodeCanvas = function (element, imageType) {
const canvas = document.createElement('CANVAS');
const context = canvas.getContext('2d');
canvas.height = element.height;
canvas.width = element.width;
context.drawImage(element, 0, 0);
// Validate imageType property
if (typeof imageType !== 'string') {
console.error('FV.cacheImage: Error - Invalid imageType property');
return null;
}
return canvas.toDataURL(`image/${imageType}`);
};
$.fn.cacheImages.testOutput = function (output, checkValue) {
// Validate output argument
if (typeof output !== 'string') {
console.error('FV.cacheImage: Error - Invalid output argument');
return false;
}
return output !== undefined && (checkValue !== true || output !== '');
};
$.fn.cacheImages.set = function (element, key, data, callback) {
try {
localStorage.setItem(key, data);
console.log(`FV.cacheImage: Stored - ${key}`);
callback(key, data);
} catch (error) {
console.error(`FV.cacheImage: Failed - ${key}`);
callback(key, data);
}
};
$.fn.cacheImages.get = function (element, key, callback) {
try {
const cachedData = localStorage.getItem(key);
callback(key, cachedData !== null && cachedData);
} catch (error) {
console.error(`FV.cacheImage: Failed Retrieval - ${key}`);
callback(key, false);
}
};
})(jQuery);