Welcome to our comprehensive guide on jQuery Lazy Loading! This tutorial is designed for both beginners and intermediates, focusing on practical examples and real-world applications. By the end of this lesson, you'll understand the concept of lazy loading, its benefits, and how to implement it using jQuery. š Note: Lazy loading improves website performance by delaying the loading of images until they are needed, thus reducing initial load time.
Lazy loading is a technique used to improve website performance by loading resources (usually images) only when they enter the viewport (the visible area of a web page). This means that images located below the fold won't load until the user scrolls down, making the initial page load faster.
First, let's set up our HTML and include the jQuery library in our project.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Lazy Loading Tutorial</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- Images for lazy loading -->
<img data-src="image1.jpg" class="lazy-load">
<img data-src="image2.jpg" class="lazy-load">
<img data-src="image3.jpg" class="lazy-load">
<!-- jQuery lazy loading script -->
<script>
$(function () {
// Your lazy loading code here
});
</script>
</body>
</html>š Note: We've added a data-src attribute to our images, which will hold the actual image source until it needs to be loaded. The lazy-load class will be used to target these images in our jQuery code.
Now that we've set up our HTML, let's implement the lazy loading functionality using jQuery.
$(function () {
// Wait for the window to scroll
$(window).scroll(function () {
// Check if the image is in the viewport
$('.lazy-load').each(function () {
// Calculate the position of the image center and the top of the viewport
var imgPos = $(this).offset().top;
var viewportHeight = $(window).height();
var imgCenter = $(this).height() / 2;
// Check if the image center is less than the viewport height plus the image center
if (imgPos - imgCenter < viewportHeight) {
// Load the image
$(this).attr('src', $(this).data('src'));
}
});
});
});This script uses the scroll event to detect when the user scrolls down the page. For each image with the lazy-load class, it calculates the position of the image center and the top of the viewport. If the image center is less than the viewport height plus the image center, the image is loaded by setting its src attribute to the value stored in the data-src attribute.
For more advanced use cases, you can consider using plugins like LazyLoad, which provide additional features and optimizations.
What is Lazy Loading? š” **Pro Tip:**
Why is lazy loading beneficial for website performance? š” **Pro Tip:**