Implementation and Optimization of Lazy Loading for DIV Background Images Using jQuery

Dec 02, 2025 · Programming · 11 views · 7.8

Keywords: lazy loading | background images | jQuery plugin | performance optimization | IntersectionObserver

Abstract: This paper provides an in-depth analysis of technical solutions for lazy loading DIV background images in web development. By examining the core mechanisms of the jQuery Lazy Load plugin, it proposes modification strategies tailored for background images, detailing key steps such as data attribute configuration, image loading triggers, and dynamic CSS style application. Through code examples, the article demonstrates how to distinguish between regular images and background images using custom data-background attributes, and utilizes the load event of img tags to ensure background styles are applied only after complete image loading. Additionally, it compares traditional event listeners with the modern IntersectionObserver API, offering developers a comprehensive technical path from basic implementation to performance optimization.

Technical Background and Problem Analysis

In the field of web performance optimization, lazy loading of images has become a key technique for improving page load speed and user experience. Traditional lazy loading primarily targets <img> tags, delaying the loading of images outside the viewport to reduce initial requests. However, in practical development, many DIV elements use the CSS background-image property for background images, which also require lazy loading mechanisms. The user's question is based on the jQuery Lazy Load plugin and how to extend its functionality to support lazy loading of DIV background images.

Core Implementation Principles

The core of implementing lazy loading for DIV background images lies in modifying the plugin's event handling logic to recognize and process background image resources. The original plugin stores image URLs in the data-original attribute and dynamically creates <img> tags to load images when elements enter the viewport. For background images, we need to add custom data attributes (e.g., data-background) to distinguish resource types and apply the image URL to the CSS background-image property instead of the img's src attribute after loading.

Detailed Code Implementation

First, add a data-background attribute to DIV elements requiring lazy-loaded background images in the HTML structure, for example: <div data-background="http://example.com/image.jpg" id="targetDiv"></div>. In the JavaScript section, modify the plugin's appear event handler with key code as follows:

if (settings.appear) {
    var elements_left = elements.length;
    settings.appear.call(self, elements_left, settings);
}
var loadImgUri;
if ($self.data("background"))
    loadImgUri = $self.data("background");
else
    loadImgUri = $self.data(settings.data_attribute);

$("<img />")
    .bind("load", function() {
        $self.hide();
        if ($self.data("background")) {
            $self.css('backgroundImage', 'url(' + $self.data("background") + ')');
        } else {
            $self.attr("src", $self.data(settings.data_attribute));
        }
        $self[settings.effect](settings.effect_speed);
        self.loaded = true;
        var temp = $.grep(elements, function(element) {
            return !element.loaded;
        });
        elements = $(temp);
        if (settings.load) {
            var elements_left = elements.length;
            settings.load.call(self, elements_left, settings);
        }
    })
    .attr("src", loadImgUri);

This code first checks if the element has a data-background attribute to determine the image URL to load. It then creates a temporary <img> tag to preload the image, ensuring the resource is fully available. In the load event callback, if data-background is detected, the image is set as the DIV's background via $self.css('backgroundImage', 'url(...)'); otherwise, the original logic for setting the img's src attribute is used. This design maintains backward compatibility while extending support for background images.

Performance Optimization and Alternative Solutions

Beyond jQuery-based solutions, modern browsers offer more efficient lazy loading implementations. The IntersectionObserver API allows developers to monitor the intersection state of elements with the viewport without frequent scroll event calculations, significantly improving performance. Example code is as follows:

document.addEventListener("DOMContentLoaded", function() {
    var lazyBackgrounds = [].slice.call(document.querySelectorAll(".lazy-background"));
    if ("IntersectionObserver" in window) {
        let lazyBackgroundObserver = new IntersectionObserver(function(entries, observer) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add("visible");
                    lazyBackgroundObserver.unobserve(entry.target);
                }
            });
        });
        lazyBackgrounds.forEach(function(lazyBackground) {
            lazyBackgroundObserver.observe(lazyBackground);
        });
    }
});

Combined with CSS class toggling (e.g., from .lazy-background to .visible), smooth background image loading effects can be achieved. This approach reduces jQuery dependency and is more suitable for modern web applications.

Practical Recommendations and Conclusion

In real-world projects, choosing a lazy loading solution should consider browser compatibility, project technology stack, and performance requirements. For traditional jQuery projects, modifying existing plugins is a quick and feasible option; for new projects, using the native IntersectionObserver API is recommended for better performance. Regardless of the approach, user experience during image loading should be ensured, such as by adding loading placeholders or transition animations. By properly implementing lazy loading for DIV background images, initial page load can be effectively reduced, enhancing overall website performance.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.