Search code examples
bootstrap-4thymeleaflazy-loadingpinterest

How to use Bootstrap to Lazy loading pinterest looking images with thymeleaf template engine


I have following bootstrap code to present pinterest like images. I am using thymeleaf template engine. I have many images to show. I am experiencing slow downloading many images issue. I have searched image lazy loading. There are approaches such as using data-src, data-echo. However, I am using thymeleaf to resolve image URL dynamically at runtime, so image src needs to be specified as th:src attribute as below. Hence, data-src and data-echo does not work for me. Search on web, there is no thymeleaf related lazy loading discussions.

Any one know how to resolve this many image download issue ?

  <div class="container">
   <div class="row">
      <div class="card-columns">
         <div class="card card-pin" th:each="product : ${Products}">
            <img class="card-img" id="productDetail" th:src="${product.href}" alt="Card image" th:onclick="'getProductDetail(\'' + ${product.itemNumber} + '\')'" />
            <span class="text-justify" th:text="${product.name}">productName</span>
         </div>
      </div>
   </div>
</div>

Solution

  • There's no reason you can't use data-src and data-echo attributes. Simply prefix them with th:. Like this:

    <img class="card-img" id="productDetail" th:data-src="${product.href}" alt="Card image" th:onclick="'getProductDetail(\'' + ${product.itemNumber} + '\')'" />
    

    or

    <img class="card-img" id="productDetail" th:data-echo="${product.href}" alt="Card image" th:onclick="'getProductDetail(\'' + ${product.itemNumber} + '\')'" />