Shubham
Shubham

Reputation: 31

Lazy Loading HTML5 Section with Images

I have a portfolio section on my single page site (site is divided into sections by HTML5 section Tag).

 <section id="portfolio" class="light-bg">

The portfolio section contains all images ( 16 MB).

<!-- Portfolio item -->
    <div class="item graphic-design">
      <a href="#folio-popup">
        <img src="img/portfolio/graphic-design/felicity/2.jpg" alt="Portfolio"/>
        <div class="details">
        <h4 class="title">Felicity</h4>
             <p class="des decription">
              6 day count down teaser for Felicity'14.
             </p>
        </div>
         <i class="icon-share-alt"></i>
           <div class="overlay"></div>
         </a>
    </div>
<!-- /Portfolio item -->

The site has a preloader which loads the site only after all content is downloaded causing a lot of waiting time.

Is there a lazy loading technique that can be applied on HTML5 sections which would cause the Portfolio section images to load only when the 'Portfolio' section is clicked? This would save on the preloading time.

The site is here and its files are here. The index.html ( which has all sections is here.

Any other advice on how load time could be optimized?

Upvotes: 0

Views: 2289

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92471

You can change the <img>s to something like:

<img data-src="img/portfolio/graphic-design/felicity/2.jpg" alt="Portfolio"/>

and change the data-src attribute to src with JavaScript when needed, for example when Portfolio section is clicked.

Example JavaScript code:

someElement.addEventListener("click", function() {
  Array.from(document.querySelectorAll("img[data-src]"))
    .forEach(element=> {
      element.src = element.getAttribute("data-src")
      element.removeAttribute("data-src")
    })
})

jQuery version:

$jQueryElement.click(function() {
  $("img[data-src]").attr("src", function() {
    return $(this).attr("data-src")
  }).removeAttr("data-src")
})

Upvotes: 2

Related Questions