How to efficiently preload images in javascript?

0

I wanted to know if there is a function, some library or anything that facilitates the preloading of images. Does requirejs work for this? I'm doing so at the moment:

var imgs = [];
imgs["cartas"] = [];
imgs["cartas"]["ouros"] = [];
imgs["cartas"]["espadas"] = [];
imgs["cartas"]["copas"] = [];
imgs["cartas"]["paus"] = [];
imgs["cartas"]["versos"] = [];
imgs["cartas"]["versos"]["azul"] = [];
imgs["cartas"]["versos"]["verde"] = [];
imgs["cartas"]["versos"]["vermelho"] = [];
for (var i = 0; i < 10; i++) {
    imgs["cartas"]["ouros"].push(loadImg('img/cartas/ouros/carta${i}.png'));
    imgs["cartas"]["espadas"].push(loadImg('img/cartas/espadas/carta${i}.png'));
    imgs["cartas"]["copas"].push(loadImg('img/cartas/copas/carta${i}.png'));
    imgs["cartas"]["paus"].push(loadImg('img/cartas/paus/carta${i}.png'));
    if (i > 0 && i < 6) {
        imgs["cartas"]["versos"]["azul"].push(loadImg('img/cartas/versos/azul${i}.png'));
        imgs["cartas"]["versos"]["verde"].push(loadImg('img/cartas/versos/verde${i}.png'));
        imgs["cartas"]["versos"]["vermelho"].push(loadImg('img/cartas/versos/vermelho${i}.png'));
    }
}
    
asked by anonymous 25.08.2017 / 02:19

2 answers

0

I've been doing a search and I saw that there is no magic function to load images in javascript, what I did was just that:

var imgs = [];
imgs["versos"] = [];
for (var i = 0; i < 10; i++) {
    imgs['ouros${i}'] = (new Image()).src = 'img/cartas/ouros/carta${i}.png';
    imgs['espadas${i}'] = (new Image()).src = 'img/cartas/espadas/carta${i}.png';
    imgs['copas${i}'] = (new Image()).src = 'img/cartas/copas/carta${i}.png';
    imgs['paus${i}'] = (new Image()).src = 'img/cartas/paus/carta${i}.png';
    if (i > 0 && i < 6) {
        imgs["versos"]['azul${i}'] = (new Image()).src = 'img/cartas/versos/azul${i}.png';
        imgs["versos"]['verde${i}'] = (new Image()).src = 'img/cartas/versos/verde${i}.png';
        imgs["versos"]['vermelho${i}'] = (new Image()).src = 'img/cartas/versos/vermelho${i}.png';
    }
}

You've improved a bit.

    
25.08.2017 / 03:23
0

Here you have a simple function to pre-load your images

I always liked this particular case is simple.

All your images will be stored in array images .

var images = [];
function preload() {
    for (var i = 0; i < arguments.length; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i];
    }
}

// exemplo como usar
preload(
    "http://meusite.com/img/001.jpg",
    "http://meusite.com/img/002.jpg",
    "http://meusite.com/img/003.jpg"
)

Learn more

    
25.08.2017 / 15:33