Lazy loading is a technique to make your website faster by loading images or content only when it’s needed, like when it’s visible on the screen. This helps save bandwidth and makes your site load quicker, especially for users on mobile devices or slower connections.
In this post, I’ll show you how to implement lazy loading in CodeIgniter 4 (CI4) for images and content. Let’s dive in!
1. What is Lazy Loading?
Lazy loading means loading something only when it’s needed, instead of loading everything when the page loads. This is especially useful for images and videos, which can take up a lot of space and slow down page load times.
2. What You Need
Before we start, make sure you have:
- CodeIgniter 4 (CI4) already set up.
- Basic knowledge of how views and controllers work in CI4.
- Some basic knowledge of HTML and JavaScript.
3. Lazy Loading Images in CI4
Let’s start with images. Normally, images are loaded when the page loads, but with lazy loading, images will only load when they become visible to the user (like when they scroll to it).
Step 1: Use a Lazy Load Library
CI4 doesn’t have lazy loading built-in, so we’ll use LazyLoad.js, a small JavaScript library for this. You can get it from a CDN or download it.
Here’s how to include it in your layout file (e.g., app/Views/layouts/main.php):
<!-- Include LazyLoad JS Library -->
<script src="https://cdn.jsdelivr.net/npm/lazyload@3.2.0/lazyload.min.js"></script>
Step 2: Update Your Image Tags in Views
Now, go to your views (for example, app/Views/blog/index.php) and update your image tags. Instead of using the src attribute, we’ll use data-src.
Here’s how:
<img class="lazyload" data-src="<?= base_url('uploads/images/' . $post['image']) ?>" alt="<?= esc($post['post_title']) ?>" />
What’s going on here?
- We replace
srcwithdata-src, which holds the actual image URL. - We add a class
lazyloadto each image so that LazyLoad.js knows which images to lazy-load.
Step 3: Set Up Lazy Load with JavaScript
Now we need to initialize the LazyLoad.js library. Add this script to your layout or specific view:
<script>
document.addEventListener('DOMContentLoaded', function () {
var lazyloadImages = document.querySelectorAll('img.lazyload');
if ('IntersectionObserver' in window) {
let observer = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
let image = entry.target;
image.src = image.getAttribute('data-src');
image.classList.remove('lazyload');
observer.unobserve(image);
}
});
});
lazyloadImages.forEach(function (image) {
observer.observe(image);
});
} else {
// Fallback for older browsers
lazyloadImages.forEach(function (image) {
image.src = image.getAttribute('data-src');
});
}
});
</script>
This script does two things:
- It waits for the page to load, then starts lazy loading the images using the
IntersectionObserverAPI. - For browsers that don’t support
IntersectionObserver, it loads the images immediately (fallback).
Step 4: Add Some CSS for Lazy-Loaded Images
You can add some styles to make your lazy-loaded images look better while they’re loading (for example, by showing a placeholder):
img.lazyload {
opacity: 0;
transition: opacity 0.3s ease-in;
}
img.lazyload[data-src] {
background: url('path/to/placeholder-image.jpg') no-repeat center center;
background-size: cover;
}
img.lazyload.loaded {
opacity: 1;
}
This will make the images fade in when they are fully loaded.
4. Lazy Loading Content (Optional)
Lazy loading isn’t just for images. You can also use lazy loading for blog posts, comments, or any other content. One common way to do this is using AJAX to load more content as the user scrolls down.
Step 1: Add a Route for Loading More Posts
In app/Config/Routes.php, add a route for fetching more posts:
$routes->get('/blog/load-more', 'Blog::loadMore');
Step 2: Create a Method to Fetch More Posts
In app/Controllers/Blog.php, create the loadMore method to fetch more posts:
public function loadMore()
{
$page = $this->request->getGet('page') ?? 1;
$posts = $this->blogModel->getPosts($page);
return view('blog/_posts', ['posts' => $posts]);
}
Step 3: Use AJAX to Load More Posts
Finally, add this JavaScript to load more posts as the user scrolls:
document.addEventListener('DOMContentLoaded', function () {
let page = 1;
let loading = false;
window.addEventListener('scroll', function () {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight && !loading) {
loading = true;
page++;
fetch(`/blog/load-more?page=${page}`)
.then(response => response.text())
.then(data => {
document.querySelector('.posts-grid').innerHTML += data;
loading = false;
});
}
});
});
This script checks when the user scrolls to the bottom and then loads more posts via AJAX.
5. Conclusion
And that’s it! You’ve successfully implemented lazy loading in your CodeIgniter 4 app. Now your images and content will load only when they are needed, which means faster load times and a smoother user experience.
With just a few changes to your views and a little JavaScript, you can make your site much more efficient. You can even extend this to other things like videos and iframes!
Good luck and happy coding!