@@ -24,6 +24,12 @@ const modifierFields = [
24
24
] ;
25
25
export const isGif = ( mimetype ) => mimetype === 'image/gif' ;
26
26
27
+ /**
28
+ * applyModifications cache
29
+ * @type {Object.<string, ApplyModificationsReturnType> }
30
+ */
31
+ const applyModificationsCache = { } ;
32
+
27
33
// webgl color filters
28
34
const _applyAll = ( result , filter , filters ) => {
29
35
filters . forEach ( f => {
@@ -199,14 +205,19 @@ const glFilters = {
199
205
applyAll ( filter , filters ) ;
200
206
} ,
201
207
} ;
208
+
209
+ /**
210
+ * @typedef {{dataURL: string, mimetype: string} } ApplyModificationsReturnType
211
+ */
202
212
/**
203
213
* Applies data-attributes modifications to an img tag and returns a dataURL
204
214
* containing the result. This function does not modify the original image.
215
+ * Caches results in memory for better performance.
205
216
*
206
217
* @param {HTMLImageElement } img the image to which modifications are applied
207
218
* @param {boolean } returnResultWithMimetype false by default to not break
208
219
* compatibility, *must* be set to true. TODO: remove in master
209
- * @returns {Promise<{dataURL: string, mimetype: string} > } dataURL of the image
220
+ * @returns {Promise<ApplyModificationsReturnType > } dataURL of the image
210
221
* with the applied modifications and the actual output mimetype.
211
222
*/
212
223
export async function applyModifications ( img , dataOptions = { } , returnResultWithMimetype = false ) {
@@ -216,6 +227,19 @@ export async function applyModifications(img, dataOptions = {}, returnResultWith
216
227
quality : '75' ,
217
228
forceModification : false ,
218
229
} , img . dataset , dataOptions ) ;
230
+
231
+ const cacheKey = JSON . stringify ( data ) ;
232
+ const cachedResult = applyModificationsCache [ cacheKey ] ;
233
+ if ( cachedResult ) {
234
+
235
+ // TODO: remove in master, see jsdoc for returnResultWithMimetype parameter
236
+ if ( ! returnResultWithMimetype ) {
237
+ return cachedResult . dataURL ;
238
+ }
239
+
240
+ return cachedResult ;
241
+ }
242
+
219
243
let {
220
244
width,
221
245
height,
@@ -359,18 +383,20 @@ export async function applyModifications(img, dataOptions = {}, returnResultWith
359
383
: await _loadImageDataURL ( originalSrc ) ;
360
384
}
361
385
386
+ let returnValue ;
362
387
if ( isChanged || originalSize >= newSize ) {
363
- return {
388
+ returnValue = {
364
389
dataURL : imageData . dataURL ,
365
390
mimetype : imageData . mimetype ,
366
391
} ;
367
392
} else {
368
393
const originalDataURL = await _loadImageDataURL ( originalSrc ) ;
369
- return {
394
+ returnValue = {
370
395
dataURL : originalDataURL ,
371
396
mimetype : extractMimetypeFromDataURL ( originalDataURL ) ,
372
397
} ;
373
398
}
399
+ return ( applyModificationsCache [ cacheKey ] = returnValue ) ;
374
400
}
375
401
376
402
/**
0 commit comments