Calling image onload inside a loop with global variable


The variable menuitems is a key value pair. The key contains the name and the value contains the Image url. The idea is to store the below URL in the localstorage.

Local Storage variable is key_icon (key is the name of the image)

Below is the code. Assume there are 4 keys as account, sms, group and history.

$.each(menuitems, function(key, value) {
    menu_icon_session_name = key+'_icon';
    var dataImage = localStorage.getItem(menu_icon_session_name);

    //The Div container to load the image
    div  = "<div class='ui-block-a'><div class='ui-bar' id='div_"+key+"' style='padding:5px'>" +
    "<img crossorigin='anonymous' width=150 height=150 id='btn_"+key+"' style='height: 100%; width:100%'>"
    "</div></div>";

    //Append the div container with empty image
    jQuery('#pg_home_content').append(div);

    //Based on the local storage load the image
    if(dataImage){
        console.log('loaded from session');
        bannerImg = document.getElementById('btn_'+key);
        bannerImg.src = dataImage;
        jQuery('#div_'+key).html(bannerImg);
    }else{
        console.log('loaded from url');
        bannerImage = document.getElementById('btn_'+key);
        bannerImage.setAttribute('crossOrigin', 'anonymous');

        bannerImage.src = value.menu_icon;
        bannerImage.onload = function () {
            imgData = getBase64Image(bannerImage);
            localStorage.setItem(menu_icon_session_name, imgData);
            console.log('stored '+menu_icon_session_name);
        }
    }
});

Since the onload is asynchronous the variable menu_icon_session_name is overwritten and all images are stored on the last variable history_icon.

All I am trying to do is load all the 4 images to separate localstorage and use it later...

Answer

...stuff...

    bannerImage.src = value.menu_icon;
    bannerImage.attr('data-my-session-name', menu_icon_session_name);
    bannerImage.onload = function () {
        imgData = getBase64Image(this);
        localStorage.setItem($(this).attr('data-my-session-name'), imgData);            

...stuff...
source: stackoverflow.com
js interview questions