Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preload images with multiple srcset with javascript or jQuery?

I'm trying to build a script to preload images with jQuery, for a small application I'm working on.

I've read different tutorials and right now I managed to have it working like this:

var imageList = ['img1.png', 'img2.png', 'img3.png'];
$.each(imageList, function (index, imageName) {
    var $img = $('<img>')[0];
    $img.onload = function () {
        console.log('loaded');
    };
    $img.src = imgPath + imageName;
}

This works fine. I load the images from an array I prepare, I then create all the img tags and then append them in the DOM where needed.

I'm wondering now, though, how can I do something similar if I have images with multiple srcset.

Let's say I have 3 sizes for each image, but they could be more, normally I would put something like this in the html:

<img srcset="large.jpg 1024w,
      medium.jpg 640w,
      small.jpg 320w"
   sizes="(min-width: 36em) 33.3vw, 100vw"
   src="small.jpg">

Now, how shall I apply the preloading to this?

1) I could preload all the sizes for each image in Javascript, but this would be pointless, because the whole purpose of having multiple srcset is to load just one 2) I could put the img tag in the DOM, let the browser choose the only size needed and load from Javascript.

The problem with the second option is that the browser is loading the images from the DOM, so why loading them again in Javascript? It's possible that I am completely wrong about this and maybe I'm missing something. What's the correct way to do it?

like image 242
Carlo Avatar asked Nov 20 '22 14:11

Carlo


1 Answers

You can use the same idea that you had in your script, but instead set the sizes and srcset attributes.

const image = new Image()
image.onload = () => console.log('loaded')
image.sizes = '(min-width: 36em) 33.3vw, 100vw' 

// This will trigger the browser to start loading the appropriate picture
image.srcset = `
  large.jpg 1024w,
  medium.jpg 640w,
  small.jpg 320w
`
like image 97
Thibaut Remy Avatar answered Nov 23 '22 04:11

Thibaut Remy