# Lazy-Load Background Images

> Loads background images only when their section is about to scroll into view, for any element marked with data-wpide-bg="image-url", saving bandwidth on long landing pages.

- Type: JavaScript
- Runs: Site-wide footer
- Category: [Frontend & Design](https://wpide.com/library/category/frontend/)
- Tags: lazy-load, images, performance
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/frontend-lazy-background-images/

## Code

```javascript
(function () {
    var els = document.querySelectorAll('[data-wpide-bg]');
    if (!els.length) { return; }
    function load(el) {
        var url = el.getAttribute('data-wpide-bg');
        if (url) { el.style.backgroundImage = 'url("' + url.replace(/["\\]/g, '') + '")'; }
        el.removeAttribute('data-wpide-bg');
    }
    if (!('IntersectionObserver' in window)) { els.forEach(load); return; }
    var io = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) { io.unobserve(entry.target); load(entry.target); }
        });
    }, { rootMargin: '300px 0px' });
    els.forEach(function (el) { io.observe(el); });
})();
```

## Notes

Add data-wpide-bg="https://example.com/image.webp" to an element in a Custom HTML block or theme template. Elements already on screen load immediately.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Lazy-Load Background Images" in its snippet library and add it in one click; or create a new JavaScript snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
