Search code examples
phpjavascripthtmlpagespeed

Sending the right size of image depending on window size


I'm developing an image hosting website, mainly just to learn the ropes, and I'm using php and mysql, as well as html, css, and javascript.

As it is, on an image page, it loads up the full-size image, and the squishes it into a box in the layout. I get that that isn't the right thing to do; I should be sending the image that is already the right size. But here's the trouble: the box that the image is resized to fit into is based on the browser window's size. So it's a larger image if the page is larger, and a smaller image if the page is smaller.

One solution I thought of would be to store the image in several different sizes, then use javascript on the page to determine the window size, then the box's size, and then use that information to choose the right image to load. But all that inline javascript seems like it would slow things down a lot as well.

What's the best solution for this? What if the only thing I'm aiming for is speed? What if I have limited space to store multiple sizes of images? What if I have limited computing power?

I'm trying to learn about this stuff; not just implement it. Indecisive answers that analyse various options would be great.


Solution

  • You should be able to detect the window size in JavaScript before the document even loads, so the would really be no performance hit in assessing the window sizing and then loading the proper image (which would have been a second request anyway). You should just check the window size, create a single PHP script which takes the desired image size, and then use that to pull in the proper image after the document is loaded by attaching arguments to the img src attribute. Really no matter how you do it along those lines the performance impact will be insignificant since images are by default distinct requests and that will be your bottleneck.

    If you have limited space and a lot of images you could use PHP to dynamically create the image per request (with adjusted caching). If you had limited computing power you'd want to cache more heavily or you could have the images pre-made if you have a small set of possibilities. Alternately you could have certain "milepost" types of images since image resampling with a large variance normally has to be done in multiple passes, so each milepost could allow for fewer passes to sample down to the desired exact size.

    If transfer speed was theoretically a major concern you could also use image slicing. Since most clients will allow for 2+ consecutive connections to the same host you could split the image if it was large enough to warrant it (offsetting the cost of request initiation) and then display the sections merged on the page (kind of like multiplexing).