EN
JavaScript - image lazy loading
3 points
In this article, we would like to show you how to create image with lazy loading using JavaScript.
Quick solution:
xxxxxxxxxx
1
var image = document.createElement('img');
2
3
image.src = '/path/to/image.png';
4
image.loading = 'lazy';
5
6
document.body.appendChild(image);
or:
xxxxxxxxxx
1
var image = new Image();
2
3
image.src = '/path/to/image.png';
4
image.loading = 'lazy';
5
6
document.body.appendChild(image);
In this example, we create a reusable function to append images with a given url
in the specified parent
element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
function appendImage(parent, url) {
7
var image = document.createElement('img');
8
image.src = url;
9
image.loading = 'lazy';
10
parent.appendChild(image);
11
}
12
13
appendImage(document.body, 'https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png');
14
appendImage(document.body, 'https://dirask.com/static/bucket/1590005168287-pPLQqVWYa9--image.png');
15
appendImage(document.body, 'https://dirask.com/static/bucket/1590005138496-MWXQzxrDw4--image.png');
16
appendImage(document.body, 'https://dirask.com/static/bucket/1590005318053-3nbAR5nDEZ--image.png');
17
18
</script>
19
</body>
20
</html>