To start we need to group the images into 3 categories:
- Critical images — these images will always load
- Must-have images — these images should always load
- Non-critical images — it’d be nice if these images loaded
Of course—the images themselves may just fail to load because of slow Internet—there’s nothing we can do to mitigate that.
For this exercise, we’ll say the first 2 images are critical, the next 2 are must-have, and the rest are non-critical images.
Let’s adjust our HTML to group the images into our three categories.
⋮
</head>
<body>
<div class="grid">
{% for img in site.data.images limit:2 %}
<div class="critical-img unit xs-1 m-1-2">
<div class="embed embed-16by9">
<img class="embed-item" src="images/{{img}}" alt="">
</div>
</div>
{% endfor %}
{% for img in site.data.images offset:2 limit:2 %}
<div class="non-critical-img unit xs-1 m-1-2">
<div class="embed embed-16by9">
<img class="embed-item" data-src="images/{{img}}" alt="" hidden>
<noscript>
<img class="embed-item" src="images/{{img}}" alt="">
</noscript>
</div>
</div>
{% endfor %}
{% for img in site.data.images offset:4 %}
<div class="non-critical-img unit xs-1 m-1-2" hidden>
<div class="embed embed-16by9">
<img class="embed-item" data-src="images/{{img}}" alt="">
</div>
</div>
{% endfor %}
</div>
</body>
</html>
In the code above we have three loops, each has a specific purpose and ties to the our image categories:
- The images in the first loop will always show.
- The images in the second loop will show with or without JavaScript, essentially they will also always show.
- The images in the third loop will only show when the JavaScript is triggered.
Why bother having the second loop at all if they’re always going to show? To help the page load faster. Most (almost all) browsers have JavaScript enabled, so these images can be triggered later with JavaScript. The page will load super quick, showing only the images in the first loop, then the JavaScript will kick in and start downloading the rest—but our user will already have a nice, complete page.