Skip to content

Instantly share code, notes, and snippets.

@isaumya
Last active November 14, 2019 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaumya/5a3e7f582934bd4f2d98d6c17bac7690 to your computer and use it in GitHub Desktop.
Save isaumya/5a3e7f582934bd4f2d98d6c17bac7690 to your computer and use it in GitHub Desktop.
Native Browser Lazy Loading - Take Advantage Of It Instead Of Using JavaScript Plugin (Take Work Out of Your Browser Main Thread) 🥳

Native Browser Lazy Loading - Currently supported in Chrome Desktop & Mobile 🥳

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.

Native Usage for img and iframe Tags

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

Complex Custom Lazy Loading using JavaScript

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')
  })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment