Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to preload/load large images

Preload may not be the correct term...

I have a page which loads a very large image. I wanted to wait for the large image to completly load before displaying on the page for the user.

At the moment, I have a loading gif and i'm using javascript to wait for the image to load and then replace the loading gif src with the image:

<img src="loading.gif" id="image" />
<script>
img = 'very_large_image.jpg';
var newimg = new Image();
newimg.src = img;
newimg.onload = function(){
$('#image').attr('src',img);
}
</script>

I'm wondering if there are quicker ways to load this image such as a pure CSS way or some way to force the browser to download this asset first. The code above is obviously positioned in the location where the image is expected to load. So there is code above and below.

One CSS option I thought was to position the image off the screen and once it's loaded, perform the src replace.

My server is running http2, so it should be pretty quick. I just want to know if there is a better way then what i'm doing now to ensure the large image is loaded the quickest way possible for all major browsers.

I should add, i've already done plenty of optimisation of the image file already. I'm working with high resolution photography.

Thanks!

like image 963
David Avatar asked Mar 13 '23 06:03

David


1 Answers

You can make the JPG progressive and then just let it load. Browsers will progressively display the image first blurry and then load more details.

This is the best way because user can see the image even before it's fully loaded.

Edit: On linux use jpegtran, on Windows use Photoshop or RIOT

like image 121
Radek Pech Avatar answered Mar 20 '23 05:03

Radek Pech