scroll down to load image
Lazy Load Image based on user scroll
----------------------------
HTML
<div class="section">
<h2>Lazy Load Based on user scroll</h2>
<p>This will load images dynamically, based on the position of the users scroll, and only requires jQuery.</p>
<p>To test, open your network panel and scroll down the page. You should see 200s appearing as you scroll</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/300/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/500"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/420/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/420"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/400"/>
</p>
</div>
<div class="section">
<p class="img-center">
<img src="" data-src="http://www.placecage.com/400/400"/>
</p>
</div>
------------------------------
CSS
.section{
padding:100px 0;
&:nth-child(odd){
background-color: #ccc;
}
.img-center{
text-align: center;
}
&:nth-child(1){
text-align: center;
}
}
------------------------------
JS
$(window).scroll(function() {
$.each($('img'), function() {
if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
var source = $(this).data('src');
$(this).attr('src', source);
$(this).removeAttr('data-src');
}
})
})
------------------------
source code link: https://codepen.io/espo92/pen/pozeOpO
إرسال تعليق