SimonLeCat SimonLeCat - 1 year ago 132
Javascript Question

How to defer background images without jQuery or lazy loading

Based on Patrick Sexton tutorial, I would like to defer background images in the same way I do here with


<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="your-image-here">

function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
} } }
window.onload = init;

How can I do the same using backgrounds?

<div style="background:url(your-image-here)"></div>

Answer Source

Changes needed are only how we select the element


and how we set the value (here instead of setting the src attribute, we need to set the style attribute).

EDIT: I would even avoid the attribute check (in the JavaScript) here since our selector would do it.

Mark-up (Edit code here:

<!DOCTYPE html>

<html lang="en" xmlns="">
    <meta charset="utf-8" />
    <title>Defer Image</title>

        .deferImage {
            width: 800px;
            height: 600px;


        function init() {
            var imgDefer = document.querySelectorAll('div[data-src]');
            var style = "background-image: url({url})";
            for (var i = 0; i < imgDefer.length; i++) {

                imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));

        window.onload = init;

    <div class="deferImage" data-src=""></div>

EDIT: To select by class name

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download