Skip to content

Commit 6725013

Browse files
committed
refactor(dynamicimages): optimized the functionality for dynamic images
1 parent 2ae2954 commit 6725013

2 files changed

Lines changed: 18 additions & 9 deletions

File tree

demo/index.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,9 @@ <h1>
161161
title="vimeo sample video"
162162
></iframe>
163163
</noscript>
164+
165+
<h2>dynamic images</h2>
166+
<button type="button" class="add-image">Add image</button>
164167
</main>
165168
<!-- Including other optional polyfills depending on expected browser support scope -->
166169
<script

demo/index.js

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,29 @@
11
import loadingAttributePolyfill from '../dist/loading-attribute-polyfill.module.js';
22

33
// Test for dynamically inserted images
4-
window.setTimeout(() => {
5-
let child = document.createElement('div');
6-
child.innerHTML = '<noscript class="loading-lazy"></noscript>';
7-
child = child.firstChild;
4+
let addImage = (event) => {
5+
let noscriptElement = document.createElement('noscript'),
6+
imageElement = document.createElement('img');
7+
8+
noscriptElement.classList.add('loading-lazy');
89

9-
let imageElement = document.createElement('img');
1010
imageElement.setAttribute('src', 'https://via.placeholder.com/250x150');
1111
imageElement.setAttribute('loading', 'lazy');
1212
imageElement.setAttribute('alt', '..');
1313
imageElement.setAttribute('width', '250');
1414
imageElement.setAttribute('height', '150');
15-
child.appendChild(imageElement);
15+
16+
noscriptElement.appendChild(imageElement);
17+
1618
document
17-
.getElementsByTagName('main')[0]
18-
.insertBefore(child, document.getElementsByTagName('main')[0].firstChild);
19+
.querySelector('main')
20+
.insertAdjacentElement('beforeend', noscriptElement);
1921

2022
loadingAttributePolyfill.prepareElement(
2123
document.querySelector('main noscript.loading-lazy')
2224
);
23-
}, 5000);
25+
26+
event.preventDefault();
27+
};
28+
29+
document.querySelector('button.add-image').addEventListener('click', addImage);

0 commit comments

Comments
 (0)