JSFiddle - React, Tailwind, and code Playground

by santhosh lanka

HTML

<script src="https://imgur.com/a/k1P2o"></script>
<script src="https://imgur.com/a/aMFuB"></script>
<body class="asyncImage" data-src="https://i.imgur.com/EWx6Ao5.jpg">
  
</body>

CSS

body {
  background-image: url('https://images.unsplash.com/photo-1558981806-ec527fa84c39?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80');
  background-repeat: no-repeat;
  background-size: cover;
}

.container {
  width: 700px;
  margin: 0 auto;
}

JavaScript

(() => {
  'use strict';
  // Page is loaded
  const objects = document.getElementsByClassName('asyncImage');
  Array.from(objects).map((item) => {
    // Start loading image
    const img = new Image();
    img.src = item.dataset.src;
    // Once image is loaded replace the src of the HTML element
    img.onload = () => {
      item.classList.remove('asyncImage');
      return item.nodeName === 'IMG' ? 
        item.src = item.dataset.src :        
        item.style.backgroundImage = `url(${item.dataset.src})`;
    };
  });
})();