Typically, images in web pages are external resources
— stored separately, in their own files.
Typically, the following are also external resources:
favicons
videos
audio files
CSS stylesheets
fonts
JavaScript programs
Suppose a web page references several external resources (stylesheets, images, etc.).
When a client requests the web page, the server does not send all the content in one go.
The client receives the web page and then sends a separate request for each external resource.
Suppose this web page is hosted on www.example.org
<!DOCTYPE html>
<html lang="en">
<head>
<title>Animal News!</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<figure>
<img src="images/logo.gif" alt="" />
</figure>
<main>
<h1>Welcome to Animal News!</h1>
<p>
<img src="images/dog.jpg" alt="A dog" />
Dog bites man. Man bites dog in return.
</p>
<p>
<img src="images/cat.jpg" alt="A cat">
Cat plays piano. Badly.
</p>
<p>
<img src="http://www.other.org/images/wombat.jpg" alt="A wombat">
Wombat doesn't play piano. Learns saxophone.
</p>
</main>
</body>
</html>
A minimum of 5 additional requests:
The example also illustrates the following ideas:
In the next module, we will see examples where there is a same-origin security policy, where cross-origin requests are not allowed.
Typically, CSS and JavaScript are render-blocking.
Images (including favicons), fonts, video and audio files are non-blocking.
How can we avoid multiple requests in the case of images?
Instead of putting your image in a separate file, you can produce its corresponding data URI and then include this directly in your HTML or CSS.
There are tools for converting images to data URIs.
Example of a data URI:
data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QAWRXhpZg…
<img src="photo.jpg"
alt="…" />
becomes
<img src="data:image/jpg;base64,/9j/4AAQSk…"
alt="…" />
You can use data URIs for:
external resource | data URI/ embedded resource |
---|---|
several requests/responses | one request/ one response (but bigger) |
separate caching may reduce subsequent requests |
no separate caching |
<img src="ucc.jpg" alt="..."
loading="lazy" />
loading="eager"
(default):
browser requests the image, regardless of whether it will be visible in the viewport.
loading="lazy"
:
browser defers requesting the image until the user scrolls to a point where the image will soon need to be visible in the viewport.
Monitor continuously!