I have a scrollTo function on my page where when you click on a specific button you scroll to a section with a unique ID.
The problem is I am using lazy loading for the images on my website so, this will cause the ScrollTo to stop halfway through the page because of the images which are lazy-loaded.
After all, images are loaded and I click again on the button it works just fine.
My lazy load code:
(() => {
    const runLazy = () => {
        let images = [...document.querySelectorAll('[data-lazy]')];
        const settings = {
            rootMargin: '0px',
            threshold: 0.02
        };
        let observer = new IntersectionObserver((imageEntites) => {
            imageEntites.forEach((image) => {
                if (image.isIntersecting) {
                    observer.unobserve(image.target);
                    image.target.src = image.target.dataset.lazy;
                    image.target.onload = () =>
                        image.target.classList.add('loaded');
                }
            });
        }, settings);
        images.forEach((image) => observer.observe(image));
    };
    runLazy();
})();
My scroll to code:
(() => {
    document.querySelectorAll('a[href^="#"]').forEach((elem) => {
        elem.addEventListener('click', (e) => {
            e.preventDefault();
            let block = document.querySelector(elem.getAttribute('href')),
                offset = elem.dataset.offset
                    ? parseInt(elem.dataset.offset)
                    : 0,
                bodyOffset = document.body.getBoundingClientRect().top;
            window.scrollTo({
                top: block.getBoundingClientRect().top - bodyOffset + offset,
                behavior: 'smooth'
            });
        });
    });
})();
Is there a way to fix this?
 
     
    