'Async function in for loop

I'm trying to lazy load maps in the page. As the map element intersects, I load the script an run the appendMap() function. If two maps are in the viewport, the loadScript function test for map-scipt id is faster than the script loading, and I have an error because appendMap function does not exists. How can I make this functions async to wait for the script loading at least one time ?

// Intersection Observer
const lazyInit = (element,margin,fn) => {
    const observer = new IntersectionObserver((entries) => {
        if (entries.some(({isIntersecting}) => isIntersecting)) {
            observer.disconnect();
            fn();
        }
    },{rootMargin: margin + 'px'});
    observer.observe(element);
};

// Load script
function loadScript(url,id,fn){
    var s = document.getElementById(id);
    if(!s){
        s = document.createElement('script');
        s.id = id;
        s.src = url;
        s.async = true;
        document.head.appendChild(s);
        s.onload = function(){
            fn();
        }
    } else {
        fn();
    }
}

// Maps
for(const map of document.querySelectorAll('.map')){
    lazyInit(map,600,() => {
        loadScript('/map-script.js','map-script',() => {
            appendMap(map);
        });
    });
}


Solution 1:[1]

Can you try to make the function lazyInit async ?

const lazyInit = async (element,margin,fn) => {
    const observer = new IntersectionObserver((entries) => {
        if (entries.some(({isIntersecting}) => isIntersecting)) {
            observer.disconnect();
            await fn();
        }
    },{rootMargin: margin + 'px'});
    observer.observe(element);
};
for (const map of document.querySelectorAll('.map')) {
    const lazyResp = lazyInit(map, 600, () => {
        loadScript('/map-script.js','map-script',() => {
            appendMap(map);
        });
    });
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1