Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Last active May 29, 2017 10:23
Show Gist options
  • Save Antoinebr/bdcea4d3d09cc7a0d5a008f88176c4d8 to your computer and use it in GitHub Desktop.
Save Antoinebr/bdcea4d3d09cc7a0d5a008f88176c4d8 to your computer and use it in GitHub Desktop.
lazy-loading.md

Lazy loading

For lazy loading I use lazysizes. Images can saturate the bandwith with mobile connection. We can load the images (not ATF (Above the fold) images) after the onLoad event or just before the user need them (onScroll)

Responsive images with lazy loading

Important to not display downscaled images on mobile but the perfect image size for each device size. Further more the code bellow (with lazysizes Lib) allow you to use responsive images and lazy loading at the same time.

<img
alt=""
data-sizes="auto"
data-srcset="
css/img/450x400.jpeg 300w,
css/img/450x400.jpeg 400w,
css/img/768x400.jpeg 640w,
css/img/1200x800.jpeg 1000w"
data-src="css/img/1200x800.jpeg"
class="lazyload img-responsive img-center" />

Add the lazyloadclass and prefix and set data-sizesto auto

We sometime have to load bigger images (superior to the screen width it self) because of the device pixel ratio (DPR)

Details : If we take as example the code below on a 400x736 px smarthpone with a DPR (device pixel ratio) of 1 the image that will be loaded will be the 450x400.

dpr-1.png

On the same screen size (400x736) but with a DRP of 2 the image that will be loaded will be the 1200x800

drp-2.png

Demo on code pen

Lazy loading for the background images

Include to your page this addon bgset for lazysizes

<div class="bg-video lazyload"  data-bgset="http://lorempicsum.com/simpsons/200/200/1 200w, http://lorempicsum.com/simpsons/300/300/1 300w, http://lorempicsum.com/simpsons/400/300/1 400w, http://lorempicsum.com/simpsons/768/400/1 700w" data-sizes="auto">

</div>

CSS example

.bg-video{
  width: 450px;
  height: 250px;
  max-width: 100%;
  display: block;
  margin: auto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment