html.Img Browser based lazy loading

I’m trying to use the loading attribute on an html.Img to configure image lazy loading, but it does not seem to be supported. No mention of it in the docs or anything. I’m working with dash 2.7.1.

Can sort of work around by using dash-dangerously-set-html but the DangerouslySetHtml component there isn’t serialisable so I can’t cache anything which uses this under the hood.

Am I missing something which lets me do this easily?

Help @limlom,

Welcome to the community!

Unfortunately, it does not seem to be available.

What you could do is use a callback that targets that img src, using the img id as the trigger.

So, instead of setting the src in the layout, you leave it blank and then update it in a callback that gets auto triggered once the layout loads.

1 Like

Hi @jinnyzor, thanks for the quick response!

That doesn’t quite fit my usecase sadly, i’m dynamically loading a bunch of images which won’t all be visible on the screen immediately so I only want to load them when they are scrolled into view. And obviously I don’t really want to try and replicate that lazy loading logic myself through callbacks or javascript.

Is it possible to try and get the loading attribute added to the html.Img component? (obviously not a quick solution but seems like a reasonable feature request). I’m happy to try and help if resourcing is an issue.

Alternatively figuring out how to get the DangerouslySetHtml component serialisable in a similar fashion to other dash components would also potentially be useful, though I don’t currently know enough about how that works to know if viable or not.

1 Like

You could use a markdown to render the exact tag, with dangerously_allow_html.

Here are a couple of alternatives to using the markdown from above:

I’d also recommend starting an issue on the github for this, as this could be very useful. :slight_smile:

Thanks! And good idea on the markdown compoent - I tried but no luck sadly, wonder if it’s related to the async loading of the markdown which prevents the browser from treating it properly. Opened an issue on github: [Feature Request] Add loading attribute to html.Img component · Issue #2423 · plotly/dash · GitHub

1 Like

hi @limlom ,

You can try this. But I have to tell you that this is an experimental version. :sweat_smile:

1 Like

Hi, I have a similar issue and very much appreciate your appoach. Can you elaborate on checking if layout loaded or not part? How do we check?

Hello @ramyasree,

It would be a basic callback like this:

app.clientside_callback("function (v) {return 'link'}",
Output(link, 'src'), Input(link, 'id'))

This would then change the src based upon the element getting rendered.