JavaScript added loading="lazy"

I try to add loading=“lazy” when an image or video is loaded.

As I do not like hard coded inside HTML, I try to manage using GTM or Javascript. Is it possible to manage using JavaScript injection?

Well what’s the issue? Hardcoding really means putting data in your source code that would better be loaded from a more appropriate source (such as a database), but using regular HTML attributes in your markup is perfectly fine.

That said, I don’t think applying a loading attribute at runtime would work – the JS would have to be loaded after the image in order to obtain a reference, so the attribute would likely be added to late. The only way around this would be to create the image element itself with JS, but then you don’t really need the loading attribute.

1 Like

FYI…
Lazy load with Js
Script type module Any script tag with type="module" is treated as a [JavaScript module] and is deferred by default.

May Thanks,
Speranza

I have an image gallery page with old-fashioned-do-it-yourself lazy loading, which is fired up after the DOM is loaded, but before images are loaded (so that if the browser does not have JS, the image thumbnails will still appear, just not lazily). At least in my case, this does work, so it may be workable to add the loading= attribute at that same point. I’m not sure it has enough browser coverage yet so I’m sticking with my own code, but it could be worth a shot.

I don’t follow the reason not to just put it in the html to begin with, though.

1 Like

Ah you mean within a DOMContentLoaded event listener? True, that might work… didn’t occur to me. ^^

Yes exactly… the huge benefit of this attribute is that you actually don’t need JS any more, unless you have some additional logic that requires more fine-grained control (such as scroll effects, for instance).

It is always possible to make it hard coded but it is never advised as we should use better ways. I like GTM and all possibilities. Maybe GTM code can avoid hard coded injections. As I understand you have to load it render blocking but other way it is not recommended.