-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathimage-optimizer-polyfill.js
More file actions
54 lines (46 loc) · 1.55 KB
/
image-optimizer-polyfill.js
File metadata and controls
54 lines (46 loc) · 1.55 KB
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
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready'
class ImageOptimizerPolyfill {
/**
* This script is loaded when EWWW Image Optimizer plugin is activated
* If Easy IO setting is activated for EWWW Image Optimizer plugin, dynamic images becomes blurry.
* This script fixes the issue by removing the &fit parameter from the srcset and src attributes
*/
init = () => {
const imgs = document.querySelectorAll( '.stk-block img' )
// Use Mutation Observer because the src and/or srcset attributes may change if using dynamic content
const MO = new MutationObserver( mutations => {
mutations.forEach( mutation => {
const img = mutation.target
if ( img.hasAttribute( 'srcset' ) ) {
let srcset = img.getAttribute( 'srcset' )
const pattern = /https?:\/\/[^\s,]+/g
const urls = srcset.match( pattern )
urls.forEach( url => {
const index = url.indexOf( '&fit' )
if ( index !== -1 ) {
const newUrl = url.slice( 0, index )
srcset = srcset.replace( url, newUrl )
}
} )
img.setAttribute( 'srcset', srcset )
}
if ( img.getAttribute( 'src' ).indexOf( '&fit' ) !== -1 ) {
const src = img.getAttribute( 'src' )
const index = src.indexOf( '&fit' )
const newSrc = src.slice( 0, index )
img.setAttribute( 'src', newSrc )
}
} )
} )
imgs.forEach( image => {
MO.observe( image, {
attributeFilter: [ 'src', 'srcset' ],
} )
} )
}
}
window.ImageOptimizerPolyfill = new ImageOptimizerPolyfill()
domReady( window.ImageOptimizerPolyfill.init )