J370
J370 Owner

AOS with lazyload

1 minute

While working on merging my websites, I started to realise that the Animate On Scroll (AOS) animations were no longer functioning, so I went ahead to try to troubleshoot. Having messed around with different values, I started to realise that when I open up inspect element, the AOS worked as if nothing had happened. That was when I came across this issue.

I tried out one of the solutions and saw this:

1
window.addEventListener('load', AOS.refresh);

which in essence is quite easy to understand. Add an event listener for load and do a refresh once it is trigerred. However, when it practice, I did not manage to make mine work.

What is happening?

Lazyload starts breaking quite a bit of things related to anchors as the position changes before and after the images are loaded. As AOS depends on getting the location of the object, the change meant that the animation occurs off-screen. In a nutshell, the animation does trigger but not at the desired location. One way to solve this is to refresh when required. Opening up the inspector or resizing the browser does this.

Solution

So I quickly did a search and filtered results on Github once I knew it was related to lazyload. There are multiple issues when using the search query for lazy load and lazyload. Having look through them, I found similar results to refresh through different triggers and found this answer to be the best for my case:

1
2
3
4
5
6
document.querySelectorAll('img')
.forEach((img) =>
    img.addEventListener('load', () =>
        AOS.refresh()
    )
);

So ultimately, I want to save on computing resources as well and only do a refresh when it is necessary. While some solutions suggest refreshing on scroll every few seconds, I can see how the site would start lagging. Instead, this solution can help to ensure that only a refresh is called when an image loads up, thus updating the position.

Hope this had helped you!

(Updated: )


Also Read

Jekyll Paginate V2 categories auto pages and normal generation

For some reasons, when I was using Jekyll Paginate V2, I had problems getting both the auto pages and generation to work seamlessly together. Auto pages always seem to give...

How I merged my blog and portfolio site

How I merged my blog and portfolio site

大工落成! Finally, after a full day of work, I managed to merge both my blog and portfolio into one individual site. This move would provide convenience when it comes to...