1

I wrote the following javascript code to load images async:

const $collection = $('#CollectionSection .grid-uniform'), $images = $collection.find('.grid-product__image'), imagesLen = $images.length; for (var i=0; i<imagesLen; i++){ setTimeout(function() { $images[imagesLen-i].src = $images[imagesLen-i].src.replace('_compact.', '_grande.'); i--; }, 100*(i+1)); } 

My question is, is this a valid code? Will this help my page load faster (assuming _compact images are really small)?

0

1 Answer 1

4

The short answer would be no. From what I gather you want to load a bunch of images separately by loading one every 100ms.

That means if you have 20 images, you'll spend 2 seconds loading, and if you have 100, you'll spend 10 seconds loading. I bet you that on a decent connection, any browser can beat that.

I would not want to pre-empt the browser on this. Just put them in as regular tags and let the browser do the rest. It is much more adept at loading resources and scheduling the loading of resources. Especially since http/2. If there's a fat pipe you'll be loading that data much faster as well.

If you do want to go this route, only use it as a response to user action. So if the user scrolls through the gallery and reaches a point where there are no more images should you add some more. But without timeouts and any special logic. Just create images or assign srcs to already created DOM elements.

If you're using http/1 you could use something like css sprites to do a single download of a big image, and have each gallery image take its source from that.

Sign up to request clarification or add additional context in comments.

2 Comments

What I really want to know is will the page render to the point of compact images faster than it would for the state of big images? It's a mobile site, and only 1 image is seen in the viewport
It's hard to say for sure. Bigger images will take longer to download for sure. But as long as you provide a width and height to the img tag, or the browser knows the size of the image via css it should not stall rendering whole the image download is happening. It shouldn't stall in general with images, but you might get a reflow when the image is ready and drawn if it doesn't fit into how the page is layed out. But if you haven't seen performance problems don't try to fix them. Wait until there's a problem, identify it, measure and fix.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.