I created a sort of lazyload (preloading images) in JavaScript with the scroll event where some images only load when they enter the visible area of the window.
For this I created a generic image of 1x1 transparent pixel ( dt.png
) and placed in the src
of the images and a data-src
attribute with the path of the respective image:
<img src="dt.png" data-src="img/foto1.jpg" class="lazyload">
<img src="dt.png" data-src="img/foto2.jpg" class="lazyload">
When doing scroll
, the JavaScript code will check if the image is inside the viewport window, if it will it will replace the value of src
with data-src
loading and displaying the image . So far so good.
I tried to do this using the ::before
pseudo-class in the <img>
tag and even works if the src
is empty:
.lazyload::before{
content: 'Carregando imagem...';
position: absolute;
right: 3px;
top: 3px;
}
div{
width: 300px;
background: red;
padding: 15px;
color: white;
text-align: center;
}
img{
position: relative;
width: 300px;
height: 200px;
}
<div>
<img src="" data-src="img/foto1.jpg" class="lazyload">
<p>Texto qualquer</p>
</div>
But with
src
empty is not interesting because it shows the " image start "as well as a border.
Now with transparent PNG, the text of ::before
does not appear (even if the PNG is transparent):
.lazyload::before{
content: 'Carregando imagem...';
position: absolute;
right: 3px;
top: 3px;
}
div{
width: 300px;
background: red;
padding: 15px;
color: white;
text-align: center;
}
img{
position: relative;
width: 300px;
height: 200px;
}
<div>
<img src="https://i.stack.imgur.com/Qk53m.png"data-src="img/foto1.jpg" class="lazyload">
<p>Tem uma imagem transparante aqui em cima</p>
</div>
Looking at the element inspection of the browser, I noticed that when the
src
is empty or with an image path that does not exist, the::before
appears, but when I put a correct image path, the::before
some.
Is there any way to make this ::before
visible even with transparent PNG in src
or another possible solution for this case using CSS?