Images Lazy Load
优质
小牛编辑
133浏览
2023-12-01
Lazy Load delays loading of images on page while they are outside of viewport until user scrolls to them.
It will make the page load faster, improve scrolling performance and also save traffic.
Note, that lazy images and elements should be inside of scrollable <div class="page-content"> to work correctly
Usage
For Images <img>
To use lazy load on images:
- specify image source into
data-src
attribute instead ofsrc
attribute - add
lazy
class to image
<div class="page-content">
...
<img data-src="path/to/image.jpg" class="lazy">
...
</div>
For Background Images
It is also possible to use lazy load for background images, in this case:
- specify element's background image source into
data-background
- add
lazy
class to element
<div class="page-content">
...
<div data-background="path/to/image.jpg" class="lazy">
...
</div>
...
</div>
That is all, after image appears in viewport, it will be loaded. After that lazy
class will be replaced with lazy-loaded
.
With Fade-in Effect
If you want to add fade-in effect when image is loaded, you need to add additional lazy-fadein
class to image/element:
<div class="page-content">
...
<img data-src="path/to/image.jpg" class="lazy lazy-fadein">
<div data-background="path/to/image.jpg" class="lazy lazy-fadein">
...
</div>
...
</div>
Trigger Lazy Load Manually
It is possible to trigger image loading by triggering "lazy" event on lazy image/element, for example:
$$('img.lazy').trigger('lazy');
$$('div.lazy').trigger('lazy');
Examples
...
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>
<img data-src="http://lorempixel.com/500/500/nature/1" width="100%" class="lazy lazy-fadeIn">
</p>
<p>Lorem ipsum dolor sit amet...</p>
<p>
<img data-src="http://lorempixel.com/500/500/nature/2" width="100%" class="lazy lazy-fadeIn">
</p>
<p>Aenean id congue orci...</p>
<p>
<img data-src="http://lorempixel.com/500/500/nature/3" width="100%" class="lazy lazy-fadeIn">
</p>
<p>Pellentesque aliquam ...</p>
...
<p><b>Using as background image:</b></p>
<div data-background="http://lorempixel.com/500/500/people/10" style="background: #aaa; height:60vw; background-size-cover" class="lazy lazy-fadeIn"></div>
<p>Suspendisse potenti. Curabitur ...</p>
</div>
</div>
</div>
...