Lazy loading is a web performance optimization technique that delays loading non-critical resources to improve website speed, reduce bandwidth usage, and enhance user experience. In PHP development, lazy loading is often used for images, audio, video, and other large file resources.
This article demonstrates how to implement lazy loading in PHP websites to improve site speed with example code.
Implementing lazy loading often relies on third-party libraries such as Lazy Load or Unveil.js. These libraries can be easily included via npm or CDN for quick use.
Here is an example using the Lazy Load library to implement image lazy loading:
<!-- Include Lazy Load library in the <head> tag --> <script src="https://cdn.jsdelivr.net/npm/lazyload/lazyload.js"></script> <!-- Add data-src attribute in the img tag to hold the real image URL, and add the lazy class --> <img class="lazy" data-src="path/to/your/image.jpg" alt="Example Image" /> <!-- Initialize the Lazy Load library --> <script> document.addEventListener("DOMContentLoaded", function() { var lazyImages = [].slice.call(document.querySelectorAll("img.lazy")); if ("IntersectionObserver" in window) { let lazyImageObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { let lazyImage = entry.target; lazyImage.src = lazyImage.dataset.src; lazyImage.classList.remove("lazy"); lazyImageObserver.unobserve(lazyImage); } }); }); lazyImages.forEach(function(lazyImage) { lazyImageObserver.observe(lazyImage); }); } }); </script>
This method ensures that images are only loaded when they enter the user’s viewport, reducing the initial page load time.
Lazy loading is not limited to images; it can also be applied to audio and video resources. By listening to page scroll events and checking whether elements are in the viewport, resources can be loaded and played dynamically.
Here is an example of lazy loading a video:
<video controls muted loop autoplay preload="none" id="lazy-video" data-src="path/to/your/video.mp4"></video> <script> document.addEventListener("DOMContentLoaded", function() { var lazyVideo = document.getElementById("lazy-video"); window.addEventListener("scroll", function() { var rect = lazyVideo.getBoundingClientRect(); var inViewPort = (rect.top >= 0 && rect.bottom <= window.innerHeight); if (inViewPort) { lazyVideo.src = lazyVideo.dataset.src; } }); }); </script>
In this example, the video uses preload="none" to prevent automatic resource loading. When the user scrolls and the video enters the viewport, it starts loading and playing, effectively reducing the initial page load pressure.
By applying lazy loading, you can significantly reduce the initial resource load for PHP websites, improving access speed and enhancing user experience. The examples in this article demonstrate how to implement lazy loading for images and videos. Developers can apply these techniques flexibly to further optimize website performance.