Technical Methods with Lazy Load Image for Your Website.

Technical Methods with Lazy Load Image for Your Website.

Lazy loading images means loading images on websites asynchronously — that is, after the above-the-fold content is fully loaded, or even conditionally, only when they appear in the browser’s viewport.

With images being among the most popular type of content on the web, page load time on websites can easily become an issue.

Even when properly optimized, images can weigh quite a bit. This can have a negative impact on the time visitors have to wait before they can access content on your website. Chances are, they get impatient and navigate somewhere else, unless you come up with a solution to image loading that doesn’t interfere with the perception of speed.

In this article, you will learn about five approaches to lazy loading images that you can add to your web optimization toolkit to improve the user experience on your website.

What Is Lazy Loading?

Lazy loading images means loading images on websites asynchronously — that is, after the above-the-fold content is fully loaded, or even conditionally, only when they appear in the browser’s viewport. This means that if users don’t scroll all the way down, images placed at the bottom of the page won’t even be loaded.

A number of websites use this approach, but it’s especially noticeable on image-heavy sites. Try browsing your favorite online hunting ground for high-res photos, and you’ll soon realize how the website loads just a limited number of images. As you scroll down the page, you’ll see placeholder images quickly filling up with real images for preview. For instance, notice the loader on Unsplash.com: scrolling that portion of the page into view triggers the replacement of a placeholder with a full-res photo:

Why Should You Care About Lazy Loading Images?

There are at least a couple of excellent reasons why you should consider lazy loading images for your website:

  • If your website uses JavaScript to display content or provide some kind of functionality to users, loading the DOM quickly becomes critical. It’s common for scripts to wait until the DOM has completely loaded before they start running. On a site with a significant number of images, lazy loading — or loading images asynchronously — could make the difference between users staying or leaving your website.
  • Since most lazy loading solutions work by loading images only if the user has scrolled to the location where images would be visible inside the viewport, those images will never be loaded if users never get to that point. This means considerable savings in bandwidth, for which most users, especially those accessing the web on mobile devices and slow-connections, will be thanking you.

Well, lazy loading images helps with website performance, but what’s the best way to go about it?

There is no perfect way.

If you live and breathe JavaScript, implementing your own lazy loading solution shouldn’t be an issue. Nothing gives you more control than coding something yourself.

Alternatively, you can browse the web for viable approaches and start experimenting with them. I did just that and came across these five interesting techniques.

#1 Lazy Loading Using the Intersection Observer API

The Intersection Observer API is a modern interface that you can leverage for lazy loading images and other content.

Here’s how MDN introduces this API:

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

In other words, what is being asynchronously watched is the intersection of one element with another.

Denys Mishunov has a great tutorial both on the Intersection Observer and on lazy loading images using it. Here’s what his solution looks like.

Let’s say you’d like to lazy load an image gallery. The markup for each image would look like this:

<img data-src="image.jpg" alt="test image">

Notice how the path to the image is contained inside a data-src attribute, not a src attribute. The reason is that using src means that the image would load right away, which is not what you want.

In the CSS, you give each image a min-height value, let’s say 100px. This gives each image placeholder (the img element without the src attribute) a vertical dimension.

img {
  min-height: 100px;
  ...more styles here
}

In the JavaScript document, you then create a config object and register it with an intersectionObserver instance:

// create config object: rootMargin and threshold
// are two properties exposed by the interface
const config = {
  rootMargin: '0px 0px 50px 0px',
  threshold: 0
};

// register the config object with an instance
// of intersectionObserver
let observer = new intersectionObserver(function(entries, self) {
  // iterate over each entry
  entries.forEach(entry => {
    // process just the images that are intersecting.
    // isIntersecting is a property exposed by the interface
    if(entry.isIntersecting) {
      // custom function that copies the path to the img
      // from data-src to src
      preloadImage(entry.target);
      // the image is now in place, stop watching
      self.unobserve(entry.target);
    }
  });
}, config);

Finally, you iterate over all of your images and add them to this iterationObserver instance:

const imgs = document.querySelectorAll('[data-src]');
imgs.forEach(img => {
  observer.observe(img);
});

The merits of this solution: it’s a breeze to implement, it’s effective, and has the intersectionObserver do the heavy-lifting in terms of calculations.

On the flip side, although the Intersection Observer API is supported by most browsers in their latest versions, it’s not consistently supported by all of them. Fortunately, a polyfill is available.

You can learn more on the Intersection Observer API and the details of this implementation in Denys’s article.

#2 Robin Osborne’s Progressively Enhanced Lazy Loading

Robin Osborne suggests a super ingenious solution based on progressive enhancement. In this case, lazy loading itself, which is achieved using JavaScript, is considered the enhancement over regular HTML and CSS.

Why progressive enhancement? Well, if you display images using a JavaScript-based solution, what happens if JavaScript is disabled or an error occurs which prevents the script from working as expected? In this case, without progressive enhancement, users are likely to see no images at all. Not cool.

You can see the details of a basic version of Osborne’s solution in this Pen, and a more comprehensive one, which takes into account the case for broken JavaScript, in this other Pen here.

This technique has a number of advantages:

  • The progressive enhancement approach ensures users always have access to content.
  • Not only does it cater for a situation where JavaScript is not available, but also for those cases when JavaScript is broken: we all know how error-prone scripts can be, especially in an environment where a significant number of scripts are running.
  • It lazy loads images on scroll, so not all images will be loaded if users don’t scroll to their location in the browser.
  • It doesn’t rely on any external dependencies, hence no frameworks or plugins are necessary.

You can learn all the details of Robin Osborne’s approach on his blog.

#3 Lozad.js

A quick and easy alternative for implementing lazy loading of images is to let a JS library do most of the job for you.

Lozad is a highly performant, light and configurable lazy loader in pure JavaScript with no dependencies. You can use it to lazy load images, videos, iframes, and more and it uses the Intersection Observer API.

You can include Lozad with npm/Yarn and import it using your module bundler of choice:

npm install --save lozad

yarn add lozad
import lozad from 'lozad';

Alternatively, you can simply download the library using a CDN and add it to the bottom of the HTML page in a < script> tag:

<script src="https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script>

Next, for a basic implementation, add the class lozad to the asset in your markup:

<img class="lozad" data-src="img.jpg">

Finally, instantiate Lozad in your JS document:

const observer = lozad();
observer.observe();

You’ll find all the details of how you can use the library on the Lozad GitHub repository.

If you don’t want to dive into the workings of the Intersection Observer API or you’re simply looking for a fast implementation that applies to a variety of content types, Lozad is a great choice.

Only, be mindful of browser support and eventually integrate this library with a polyfill for the Intersection Observer API.

#4 Lazy Loading with Blurred Image Effect

If you are a Medium reader, you have certainly noticed how the site loads the main image inside a post.

The first thing you see is a blurred, low-resolution copy of the image, while its high-res version is being lazy loaded:


You can lazy load images with this interesting blurring effect in a number of ways.

My favorite technique is by Craig Buckler. Here’s all the goodness of this solution:

  • Performance: only 463 bytes of CSS and 1,007 bytes of minified JavaScript code
  • Support for retina screens
  • Dependency-free: no jQuery or other libraries and frameworks required
  • Progressively enhanced to counteract older browsers and failing JavaScript

You can read all about it in How to Build Your Own Progressive Image Loader and download the code on the project’s GitHub repo.

#5 Yall.js

Yall is a feature-packed lazy loading script for images, videos, and iframes. More specifically, it uses the Intersection Observer API and smartly falls back on traditional event handler techniques where necessary.

When including Yall in your document, you need to initialize it as follows:

<script src="yall.min.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", yall);
</script>

Next, to lazy load a simple img element, all you need to do in your markup is:

<img class="lazy" src="placeholder.jpg" data-src="image-to-lazy-load.jpg" alt="Alternative text to describe image.">

Note the following:

  • You add the class lazy to the element
  • The value of src is a placeholder image
  • The path to the image you want to lazy load is inside the data-src attribute.

Among the benefits of Yall are:

  • Great performance with the Intersection Observer API
  • Fantastic browser support (it goes back to IE11)
  • No other dependencies necessary.

To learn more about what Yall can offer and for more complex implementations, feel free to check out the project’s page on GitHub.

Conclusion

And there you have it — five ways of lazy loading images you can start to experiment with and test out in your projects.

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!

Understanding Memoization And Dynamic Programming in Javascript

Understanding Memoization And Dynamic Programming in Javascript

In this Javascript tutorial I will explain what memoization is, how to use it, when you should use memoization, how to use memoization, what dynamic programming is, how to use memoization in dynamic programming. Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it.

Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it. Memoization is just the act of caching values so that they can be calculated quicker in the future. Memoization is really useful in all parts of programming, but where it is most useful is in dynamic programming. In this video I will explain what memoization is, how to use it, and why it is so useful especially in dynamic programming.

🧠 Concepts Covered:

  • What memoization is
  • When you should use memoization
  • How to use memoization
  • What dynamic programming is
  • How to use memoization in dynamic programming

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20