Image Lazy Load

There is one problem with using target selector to load a different sub-page.

Even if img tag is not displayed, browser is still going to load it. That is required because browser needs to calculate size of image.

While it can be solved by JavaScript, we can use a different approach (CSS only).

Take a look at this HTML:

<div style="height: 500px; width: 500px; background-image: url('some-image')" class="img"></div>

And CSS:

div.img
    background-size: contain
    background-repeat: no-repeat

How it works

This is a way to display image, while retaining lazy load capability without use of JavaScript. As long as this div is not displayed, image will not be loaded.

There is though a problem... div size is calculated by its content. Therefore it forces you to specify div size.

It limits responsiveness of such image as you're left only with media queries.

Luckily though we got flex containers which allow us to simplify setting size of div. It allows you to automatically scale either width or height by available space. With flex, you can also specify how much of the space your lazy image can take.

You'd still require to specify size (either width or height) and rely on media queries. But it is pretty good replacement of JavaScript approaches.

Example

You can take a look at how i make my image-links there.

These images will be loaded only when you display them so it works well with Single Page Website.

It is a hack

Yes, definitely. It is pretty much forces you to set sizes to such lazily loaded images. And limits responsiveness, so why would we use it?

Think about where you could use images. For example Control Elements. Sometimes you want some good looking buttons, links and etc. It would work well as such elements ain't supposed to change size.

results matching ""

    No results matching ""