@@ -11,29 +11,41 @@ class ImageOptimizerPolyfill {
1111 */
1212 init = ( ) => {
1313 const imgs = document . querySelectorAll ( '.stk-block img' )
14- imgs . forEach ( img => {
15- if ( img . hasAttribute ( 'srcset' ) ) {
16- let srcset = img . getAttribute ( 'srcset' )
17- const pattern = / h t t p s ? : \/ \/ [ ^ \s , ] + / g
18- const urls = srcset . match ( pattern )
19-
20- urls . forEach ( url => {
21- const index = url . indexOf ( '&fit' )
22- if ( index !== - 1 ) {
23- const newUrl = url . slice ( 0 , index )
24- srcset = srcset . replace ( url , newUrl )
25- }
26- } )
27-
28- img . setAttribute ( 'srcset' , srcset )
29- }
30-
31- if ( img . getAttribute ( 'src' ) . indexOf ( '&fit' ) !== - 1 ) {
32- const src = img . getAttribute ( 'src' )
33- const index = src . indexOf ( '&fit' )
34- const newSrc = src . slice ( 0 , index )
35- img . setAttribute ( 'src' , newSrc )
36- }
14+
15+ // Use Mutation Observer because the src and/or srcset attributes may change if using dynamic content
16+ const MO = new MutationObserver ( mutations => {
17+ mutations . forEach ( mutation => {
18+ const img = mutation . target
19+
20+ if ( img . hasAttribute ( 'srcset' ) ) {
21+ let srcset = img . getAttribute ( 'srcset' )
22+ const pattern = / h t t p s ? : \/ \/ [ ^ \s , ] + / g
23+ const urls = srcset . match ( pattern )
24+
25+ urls . forEach ( url => {
26+ const index = url . indexOf ( '&fit' )
27+ if ( index !== - 1 ) {
28+ const newUrl = url . slice ( 0 , index )
29+ srcset = srcset . replace ( url , newUrl )
30+ }
31+ } )
32+
33+ img . setAttribute ( 'srcset' , srcset )
34+ }
35+
36+ if ( img . getAttribute ( 'src' ) . indexOf ( '&fit' ) !== - 1 ) {
37+ const src = img . getAttribute ( 'src' )
38+ const index = src . indexOf ( '&fit' )
39+ const newSrc = src . slice ( 0 , index )
40+ img . setAttribute ( 'src' , newSrc )
41+ }
42+ } )
43+ } )
44+
45+ imgs . forEach ( image => {
46+ MO . observe ( image , {
47+ attributeFilter : [ 'src' , 'srcset' ] ,
48+ } )
3749 } )
3850 }
3951}
0 commit comments