title: Background Image with WebP fallback and data-src
body: <p>So I am doing some optimisation work on my web site to improve Page Insights scores, two points that I can address are:-</p>
  
  <ul>
  <li>Serve images in next-gen formats</li>
  <li>Defer offscreen images</li>
  </ul>
  
  <p>So images in next-gen formats, I have decided to use WebP but need to include fallbacks so they work in all browsers/devices.</p>
  
  <p>Defer offscreen images; I am using <code>data-src</code> with a bit of JS script to set the background image as the data-src, the JS replaces the initial SRC which is <code>src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="</code></p>
  
  <p>Taking the below as an example, how would I go about using inline background-image with WebP with fallbacks whilst deferring offscreen images?</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;div id="working-bg" class="parallax" data-src="/wp-content/uploads/2016/08/silva-planning-parralax.jpg" style="background-image: url(/wp-content/uploads/2016/08/silva-planning-parralax.jpg)"&gt;&lt;/div&gt;
  </code></pre>
  
  <p><strong>JS for data-src</strong></p>
  
  <pre><code>&lt;script&gt;
  function init() {
      var imgDefer = document.getElementsByTagName('img');
      for (var i=0; i&lt;imgDefer.length; i++) {
      if(imgDefer[i].getAttribute('data-src')) {
          imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
      } }
  
      var imgDeferSpan = document.querySelectorAll('span[data-src]');
      var styleSpan = "background-image: url({url})";
      for (var i = 0; i &lt; imgDeferSpan.length; i++) {
          imgDeferSpan[i].setAttribute('style', styleSpan.replace("{url}", imgDeferSpan[i].getAttribute('data-src')));
      }
  
      var imgDeferDiv = document.querySelectorAll('div[data-src]');
      var styleDiv = "background-image: url({url})";
      for (var i = 0; i &lt; imgDeferDiv.length; i++) {
          imgDeferDiv[i].setAttribute('style', styleDiv.replace("{url}", imgDeferDiv[i].getAttribute('data-src')));
      }
  
  }
  
  window.onload = init;
  
  &lt;/script&gt;
  </code></pre>
  
  <p>Thanks in advance!</p>