If you are using img
or the iframe
tag you can take advantage of the loading
attribute in your HTML and not only it will use the browser's native lazy loading (without using any plugin or javascript for it) it will also make your page faster.
Moreover as this a browser native feature you can get rid of your JavaScript plugins and in terms reduce work load on your Browser's Main Thread and making your web app/site load faster.
This feature is being supported by Chrome Desktop & Mobile as well as the new evergreen Googlebot. Checkout the Chrome Dev Summer 2019 video, also checkout this Can I Use link in case you wanna see the full browser support.
Here is how you would use it
<!-- Native lazy-loading -->
<img src="./assets/rick-and-morty/rick.png" loading="lazy" alt="Rick Sanchez">
<iframe src="/stuffs" loading="lazy"></iframe>
Checkout this article to deep dive into loading
With the help of the following JavaScript code you can create your own custom lazy-loading with the help
of Intersection Observer API.
The below code will take the source URL from data-src
and put it in src
while lazy-loading it.
const observer = new IntersectionObserver((entries) => {
entries.map(e => e.target).forEach((element) => {
if(!element.hasAttribute('data-src')) return
element.setAttribute('src', element.getAttribute('data-src'))
element.removeAttribute('data-src')
})
})