A vtex-lazyload based plugin for lazy loading Vtex components, other elements and images.
It also works for other platforms and projects.
https://codepen.io/akistapace/pen/ExRjgYw
$ npm install vtex-lazyloading
or download the file lazyloading.js
<script type="text/javascript" src="/arquivos/lazyloading.min.js"></script>
You can put this CDN in your HTML
<script src="https://cdn.jsdelivr.net/npm/vtex-lazyloading/lazyloading.min.js"></script>
And call it in your js file like this:point_down:
let lazyload = new VtexLazyload({options})
Or you can install this and export in your file
npm i vtex-lazyload
import vtexLazyload from "vtex-lazyloading";
const lazyload = new vtexLazyload({
root: null,
targets: '[data-lazy]',
margin: '300px 20px',
onRender: (e)=> {
console.log('Rendering');
if (e.classList.contains('target')) {
e.style.opacity = 0.5;
}
},
});
For images and Iframes
<img data-lazy="https://via.placeholder.com/700x400" alt="placeholder"/></noscript>
<iframe data-lazy="https://www.youtube.com/embed/Y4goaZhNt4k" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
For Vtex components
<div class="your-parentElement" data-lazy="true">
<noscript>
...
</noscript>
</div>
Params | Example | Description |
---|---|---|
targets | #id, .class, [atributes] | define all the lazy elements |
root | null, #id, .class, [atributes] | the parent container to trigger the lazy elements, if null is the entire viewport / window. |
margin | 10px | is the distance in pixels for the element to be loaded before it becomes visible in the window |
onRender | function | Executes a callback when the element is loaded |
Events
onRender: (e)=> {
console.log('Rendering element');
}
Methods
lazyload.update();
lazyload.reinit();
lazyload.destroy();
lazyload.destroyInElement('#test');
Params | Description |
---|---|
update() | Updates and picks up new items on the DOM |
reinit() | Restart the lazy loader if it has stopped with destroy or destroyInElement |
destroy() | Destroys the lazy loader instance in all elements |
destroyInElement() | Destroy the lazy load in an specific element |
Custom styles
You can use the following classes to custom style:
.--lazy-waiting { /* Uses when element is loading */ }
.--lazy-loaded { /* Uses when element is visible */ }
.--lazy-triggered { /* Uses when element is tracked */ }
.--lazy-error { /* Uses when element has an error */ }
Note: If the element is inside a parent element that is hidden, the lazy load will only occur when the parent element is visible, this is good for when we have images in menus.
Fernando Oliveira Aquistapace - Linkedin
Open source licensed under the MIT license.