SimonLeCat SimonLeCat - 2 months ago 16
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
:

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

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


How can I do the same using backgrounds?

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

L J L J
Answer

Changes needed are only how we select the element

document.querySelectorAll('div[data-src]');

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: http://codepen.io/anon/pen/rryxoK)

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Defer Image</title>

    <style>
        .deferImage {
            width: 800px;
            height: 600px;
        }
    </style>

    <script>

        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;

    </script>
</head>
<body>
    <div class="deferImage" data-src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Domestic-crested-duck-CamdenME.jpg/800px-Domestic-crested-duck-CamdenME.jpg"></div>
</body>
</html>

EDIT: To select by class name