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.
Opens WPIDE on
Code
(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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.