<div class="container my-4">
   

<h1>Defer image loading script</h1>
<p>If you have large images in a carousel, it would be a good idea to defer loading them. This will increase your page load time. This scripts adds a base 64 image placheholder in the html and then uses javascript to replace that with the actual image source. So the document loads and then loads in the images.</p>
   
   <p>
      <a href="https://developers.google.com/web/tools/chrome-devtools/network-performance/network-conditions">How to simulate a slow connection in Google DevTools</a>
   </p>
   
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAABlBMVEXR0dG/v7+g+VsXAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAACklEQVQImWNgAAAAAgAB9HFkpgAAAABJRU5ErkJggg==" data-src="https://resi.ze-robot.com/dl/aw/awesome-mountain-wallpaper-1920%C3%971080.jpg" class="img-defer">

</div>
/* 
Create base 64 images
https://www.base64-image.de/
*/
.img-defer {
   display:inline-block;
   width:100%;
   /*  Set a min-height of image   */
   min-height:100px;
}

function init() {
var imgDefer = document.getElementsByClassName('img-defer');
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;

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css

External JavaScript

This Pen doesn't use any external JavaScript resources.