/    Sign up×
Community /Pin to ProfileBookmark

native lazy loading with javascript loop

Hi,
I’m new to javascript and lazy loading, after much googling and fumbling around I came up with this:

[code]
let imgTag = “<img class=”pos” src=””
let lazyTag = “” loading=”lazy” alt=”…” />”
let imgPath = “imgs\aquarelle\main\”
fetch(“paintings.json”)
.then(response => response.json())
.then(data => {
for(let i = 0; i < data.aquarelle.length; i++){
document.querySelector(“#debug”).innerHTML
+= imgTag
+ imgPath + JSON.stringify(data.aquarelle[i].imgMain).replace(/[‘”]+/g, ”)
+ lazyTag + “<br>”
}
})
[/code]

to generate a lazy load image gallery from a JSON file
Wanted to know if using this code gives me the advantage of lazy loading, or if someone can suggest a better way to do this.
Thanks

to post a comment

1 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumAug 03.2021 — You need to use square brackets around the keyword "code":

`your code here`

Or alternatively you can use triple backticks.

I edited your posting accordingly.

AFAIK you will need some more javascript in order to perform the lazy loading. Using Intersection Observer to detect if an image is entering the viewport is state of the art. This tutorial seems to be fine:

https://medium.com/developers-tomorrow/javascript-best-practice-intersection-observer-api-for-lazy-loading-26483b8a3d55
×

Success!

Help @davidM_ME spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...