How it works
Adaptive Images does a number of things depending on the scenario the script has to handle but here's a basic overview of what happens when you load a page:
- The HTML starts to load in the browser and a snippet of JS in the
<head>writes a session cookie, storing the visitor's screen size in pixels.
- The browser then encounters an
<img>tag and sends a request to the server for that image. It also sends the cookie, because that’s how browsers work.
- Apache receives the request for the image and immediately has a look in the website's
.htaccessfile, to see if there are any special instructions for serving files.
- There are! The
.htaccesssays "Dear server, any request you get for a JPG, GIF, or PNG file please send to the
The PHP file then does some intelligent thinking which can cover a number of scenario's but I'll illustrate one path that can happen:
- The PHP file looks for a cookie and finds that the user has a maximum screen size of 480px.
- It compares the cookie value with all
$resolutionsizes that were configured, and decides which matches best. In this case, an image maxing out at 480px wide.
- It then has a look inside the
/ai-cache/480/folder to see if a rescaled image already exists.
- We'll pretend it doesn’t - the PHP then goes to the actual requested URI to find the original file.
- It checks the image width. If that's smaller than the user's screen width it sends the image.
- If it's larger, the PHP creates a down-scaled copy and saves that into the
/ai-cache/480/folder ready for the next time it's needed, and sends it to the user.
It also does a few other things when needs arise, for example:
- It sends images with a cache header that tells proxies not to cache the image whilst telling browsers they should. This avoids problems with proxy servers and network caching systems grabbing the wrong image and storing it.
- It handles cases where there isn't a cookie set; mobile devices will be supplied the smallest image, and desktop devices will get the largest.
- It compares time-stamps between the source image and the generated cache image - to ensure that if the source image gets updated, the old cached file won’t be sent.
One important thing: do not over-write any existing
.htaccess file. If you have one already, back it up. Feeling up to it? Excellent:
- Download the latest version of Adaptive Images either from the website or from the GitHub repository.
- Upload the included
adaptive-images.phpfiles to the server document-root.
<head>of your site as possible, before any other JS:
- Configure the
$resolutionsvariable at the top of the
adaptive-images.phpfile to match the breakpoints you are using for your designs.
If you already have an .htaccess file, open it in a text editor and add the code from the supplied file into your existing one. To support Retina displays use the alternate JS.