The Blue Cup is now correct, valid and accessible. That leaves the last of the questions you asked yourself at the end of the responsive design module: does it load quickly on a poor connection? Performance is also a matter of quality and, to a large extent, of accessibility: a page that takes eight seconds to appear on a phone with weak signal is, for someone visiting it from the bus, a page that doesn't exist. Speed also affects search engine rankings and how many people leave the page before they see it. The good news is that a large part of performance is decided in the HTML: in what order and with what priority the browser requests each resource. In this lesson you'll understand how the browser loads a page and how the experience is measured with the Core Web Vitals metrics; you'll learn to defer images and frames with loading="lazy", to prioritise the main image with fetchpriority, to load scripts without blocking the page with defer and async, and to set up connections early with preconnect; you'll review image optimisation, minification, compression and caching; and you'll learn to measure with Lighthouse and the Network tab. With all that, you'll complete the module.

Contents

  1. Why performance matters: Core Web Vitals
  2. How the browser loads a page
  3. Deferred images and frames: loading="lazy"
  4. Prioritising what matters: fetchpriority
  5. Image decoding (in passing)
  6. Scripts: at the end of the body, defer and async
  7. JavaScript modules (in passing)
  8. Resource hints: preload, preconnect and dns-prefetch
  9. Image optimisation (review)
  10. Minification and compression (in passing)
  11. Caching and versioning
  12. Measuring: Lighthouse and the Network tab with throttling
  13. Project: a faster Blue Cup

Why performance matters: Core Web Vitals

"Fast" is a vague word. To be able to measure it, Google proposed a set of metrics focused on what the person perceives, called Core Web Vitals. Today there are three:

Metric What it measures Question it answers Good Needs improvement Poor
LCP (Largest Contentful Paint) How long it takes to paint the largest content element visible on load (an image, a block of text) When do I see the main thing? ≤ 2.5 s ≤ 4 s > 4 s
CLS (Cumulative Layout Shift) How much the content shifts unexpectedly while loading Does the page move just as I'm about to tap something? ≤ 0.1 ≤ 0.25 > 0.25
INP (Interaction to Next Paint) How long the page takes to respond visually to interactions (click, tap, key press) Does it react straight away when I use it? ≤ 200 ms ≤ 500 ms > 500 ms
  • The thresholds are assessed on the 75th percentile of real visits: a page "passes" if at least three out of four visits have good values.
  • In 2024, INP replaced an earlier metric, FID, which only measured the first interaction.
  • There are two ways of measuring: field data (from real visits, collected by browsers and viewable, for example, in PageSpeed Insights when a site has enough traffic) and lab data (a simulated test, such as Lighthouse on your computer). In the lab there are no real interactions, so Lighthouse doesn't measure INP; instead it uses a related metric, Total Blocking Time (TBT).

You've already worked on two of them without calling them by these names: writing width and height on images (Adding Images) and using aspect-ratio (Responsive Images and Videos) prevents jumps, that is, it improves CLS. In this lesson you'll focus mainly on LCP and on not blocking the page.

How the browser loads a page

To optimise loading, you first need to understand it. Greatly simplified:

graph TD
    A["1. Requests the HTML from the server"] --> B["2. Parses the HTML from top to bottom<br/>and builds the DOM"]
    B --> C{"Does it find a resource?"}
    C -- "CSS (link in the head)" --> D["Downloads it in parallel.<br/>Blocks painting until it has it"]
    C -- "script without defer or async" --> E["Stops parsing,<br/>downloads it and runs it"]
    C -- "img, video, iframe" --> F["Downloads them in parallel,<br/>without blocking"]
    D --> G["3. Combines DOM and CSS:<br/>render tree"]
    B --> G
    G --> H["4. Calculates the position<br/>and size of each box"]
    H --> I["5. Paints on screen"]
    F --> I

The key ideas:

  • HTML is parsed in order. Whatever is near the top is discovered earlier.
  • CSS blocks painting: the browser doesn't show anything until it has the stylesheets in the head, so as not to show the page unstyled and then change it (you saw this in Linking CSS to HTML). That's why a single, lightweight stylesheet is a good idea.
  • A normal script blocks parsing: the browser stops, downloads the script, runs it and only then carries on reading the HTML. A slow script in the head leaves the screen blank.
  • Images don't block, but they compete for the connection: if the page requests twenty images at once, the important one takes longer.
  • Browsers have a preload scanner that reads the HTML ahead of the main parser to start downloads as soon as possible. That's why images and scripts declared in the HTML are discovered earlier than those requested from CSS or JavaScript.

With this model, the performance strategy boils down to: make sure the important things are discovered and requested early, the secondary things wait, and nothing blocks unnecessarily.

Deferred images and frames: loading="lazy"

By default, the browser downloads every image on the page when it loads, even if they're at the bottom and the person never gets to see them. The loading="lazy" attribute tells it to defer the download until the image is close to coming into view (known as lazy loading):

<img src="img/sourdough-400.webp" alt="Loaf of sourdough bread with a toasted crust"
     width="400" height="400" loading="lazy">
Value Behaviour
loading="eager" (default) Immediate download
loading="lazy" Downloads when the image approaches the visible area; the browser decides the distance based on the connection

It works the same way on iframe elements, as you already applied to the map and the YouTube video in Using iframes. With an iframe, the saving is even greater: an embedded map or player downloads dozens of files.

Rules of use:

  • Use it on images and frames that aren't visible when the page loads: below the first screen.
  • Never on the main image (the one that will be the LCP) or on images visible on load. If you defer the gallery's storefront image, the browser will wait until it has calculated the layout to decide whether it's on screen, and it will request it late: LCP gets worse.
  • Always with width and height (or aspect-ratio): without them, the deferred image takes up zero pixels until it arrives, and when it arrives it pushes the content down (CLS).
  • If you're not sure whether an image is "above" or "below" (it depends on the screen size), don't defer it: the penalty for deferring a visible image is greater than for loading one that isn't seen.

Prioritising what matters: fetchpriority

The browser assigns each resource a download priority. It initially gives images a low priority, and raises it when it discovers, after calculating the layout, that they're on screen. For the main image, that delay is wasted time. The fetchpriority attribute lets you state the priority from the HTML:

<img src="img/storefront.jpg" alt="The Blue Cup's storefront with its blue awning and a terrace with four tables"
     width="800" height="600" fetchpriority="high">
Value Use
fetchpriority="high" The LCP image: the main image on the page, visible on load
fetchpriority="low" Visible but secondary images, for example the hidden slides of a carousel
fetchpriority="auto" (default) Lets the browser decide
  • Use it sparingly: if you mark five images as high, none of them really has priority. One per page, two at most.
  • Inside a picture, the attribute goes on the img and applies to whichever source the browser chooses.
  • Don't combine it with loading="lazy": they contradict each other.
  • Browsers that don't support it simply ignore it.

Image decoding (in passing)

After downloading an image, the browser has to decode it (turn the JPEG or WebP into pixels). The decoding attribute suggests how to do it:

  • decoding="async": allows the rest of the page to be painted without waiting for decoding to finish.
  • decoding="sync": decodes before painting.
  • decoding="auto" (default): the browser decides.

Its effect is small and current browsers already make good decisions. You don't need it at The Blue Cup; it's enough for you to recognise it if you come across it in someone else's code.

Scripts: at the end of the body, defer and async

A <script src="…"> without special attributes stops HTML parsing while it's downloaded and run. There's a historical reason for this: a script could write HTML at that point in the document (with the old document.write function), so the browser couldn't carry on reading without running it. There are three ways to avoid the blocking:

Approach Download Execution Order between scripts When to use it
<script src> in the head Blocks parsing Immediate, blocking In order Hardly ever
<script src> at the end of the body On reaching the end On reaching the end In order The classic technique; it works, but the script is discovered late
<script src defer> in the head In parallel, without blocking When HTML parsing finishes, before the DOMContentLoaded event In order of appearance Page scripts that manipulate the DOM: the recommended option
<script src async> In parallel, without blocking As soon as it's downloaded, interrupting parsing if it hasn't finished yet No guaranteed order Independent scripts that don't depend on the DOM or on other scripts: analytics, adverts

Visually, on a timeline (each character is a moment; = HTML parsing, d script download, E execution):

No attributes, in the head:
  HTML    ===          ===========
  script     dddddEEE

At the end of the body:
  HTML    ==============
  script                dddddEEE

defer:
  HTML    ==============
  script    ddddd       EEE

async:
  HTML    =======     =======
  script    ddddd EEE
  • With defer, the download starts straight away (the preload scanner discovers the script in the head) and execution waits until the DOM is complete: the script can use getElementById without any problems, and the page is never blocked.
  • At the end of the body, the execution outcome is similar, but the download starts late, once the browser has already read all the HTML.
  • With async, execution can happen at any moment, even before the element the script is looking for exists.

defer and async only work with external scripts (with src). On a script with the code written inside it, they're ignored. That's one more reason, on top of the separation of concerns you saw in HTML Best Practices and the benefit of caching, to move scripts into their own files.

JavaScript modules (in passing)

In modern code you'll often see:

<script type="module" src="js/app.js"></script>

type="module" indicates that the file is a JavaScript module: it can import code from other files with import and export its own with export. In terms of loading, modules behave like defer by default (and they also accept async). It's the usual way of organising applications with a lot of JavaScript; at The Blue Cup, with three small, independent scripts, defer is enough.

Resource hints: preload, preconnect and dns-prefetch

The link element in the head can give the browser hints about resources it's going to need. These are called resource hints:

Hint What it does When to use it
<link rel="preload" href="…" as="…"> Downloads a specific resource for this page right away, with high priority Critical resources that the browser would discover late: a font or a main image requested from the CSS
<link rel="preconnect" href="https://…"> Opens the connection to another domain in advance (DNS resolution, connection and TLS encryption) External domains from which the page will soon request important resources
<link rel="dns-prefetch" href="https://…"> Only resolves the domain name, without connecting External domains that may be used; a lightweight alternative to preconnect

An example of preload for a custom font (The Blue Cup uses system fonts and doesn't need it):

<link rel="preload" href="fonts/headings.woff2" as="font" type="font/woff2" crossorigin>
  • as is required: it states the type of resource so that it gets the right priority and headers.
  • Fonts require crossorigin even if they're from the same site.
  • A preloaded resource that then isn't used wastes bandwidth, and the browser warns about it in the console.

Why does preconnect save time? Before downloading the first file from a new domain, the browser has to find out its address (DNS), establish the connection and negotiate encryption. On a mobile connection, that can take several hundred milliseconds. With preconnect, that work is done while the browser carries on reading the page.

Practical rules:

  • No more than two or three preconnect hints per page: every open connection uses resources, and if it isn't used within a few seconds, it's closed and the work is lost.
  • Only on the pages that use that domain, not on all of them.
  • For domains that are less certain to be used, dns-prefetch.

Image optimisation (review)

Images are usually the heaviest part of a page. In Adding Images and Responsive Images and Videos you learnt the essentials; in short:

Technique What it achieves Where you saw it
The right format: AVIF/WebP for photos, SVG for icons and drawings, PNG only when needed Much lighter files at the same quality Adding Images
picture with source type (AVIF → WebP → JPEG) Each browser receives the most efficient format it understands Responsive Images and Videos
srcset with x or with w + sizes Each screen downloads the resolution it needs Responsive Images and Videos
width and height (or aspect-ratio) No layout shifts (CLS) Adding Images
Compression on export Less weight with no visible loss —

For compression, free tools such as Squoosh (in the browser) let you compare quality and file size before saving. As a rough guide: a well-compressed 800-pixel-wide photo in WebP usually takes up between 40 and 120 KB; if your file weighs 1 MB, there's room for improvement.

Minification and compression (in passing)

Two techniques that reduce the size of text files (HTML, CSS, JavaScript) and are normally applied at publishing time, not while you're writing:

  • Minifying: removing unnecessary spaces, line breaks and comments, and shortening whatever can be shortened without changing the result. Minified CSS is a single unreadable but equivalent line. Build tools do this; never minify your source code by hand: keep working with the readable version.
  • Compressing: the server compresses the files before sending them (with the gzip or Brotli algorithms) and the browser decompresses them. For text files, the saving is usually 70% or more. It's enabled in the server configuration; most modern hosting does it by default. You can check it in the Network tab: the content-encoding response header shows gzip or br.

JPEG, WebP and AVIF images are already compressed: compressing them again with gzip saves nothing.

Caching and versioning

The browser cache keeps a copy of files that have already been downloaded so that it doesn't request them again. When someone visits the menu page after the home page, styles.css, the logo and the icons are already in their cache: the second page loads much faster. How long each file is kept is decided by the server with the Cache-Control header; you'll configure it, in passing, when you publish.

Caching raises a problem you already saw in Linking CSS to HTML: if you change styles.css, anyone who has the old version stored may keep seeing it. The simple solution is versioning with a parameter in the URL:

<link rel="stylesheet" href="css/styles.css?v=2">
<script src="js/menu-filter.js?v=2" defer></script>
  • To the browser, styles.css?v=2 is a different URL from styles.css?v=1: it downloads it again.
  • The server ignores the parameter and delivers the same file.
  • Every time you publish a change to the stylesheet or a script, increase the number on every page that links to it.

Large projects use tools that automatically add a fingerprint of its content to the file name (styles.3f9a2c.css). For a site like The Blue Cup, the ?v= parameter is enough. You don't need it while the site isn't published: you'll start using it after deployment, in Module 11.

Measuring: Lighthouse and the Network tab with throttling

Optimising without measuring is guesswork. Two DevTools tools are enough to get started.

Lighthouse, Performance category

The same as in Accessibility Testing, but ticking Performance and, preferably, Mobile mode, which simulates a mid-range phone on a slow connection. The report shows:

  • The metrics (LCP, CLS, TBT and others) with their colour-coded ratings.
  • Opportunities and diagnostics: for example, Largest Contentful Paint image was lazily loaded, Eliminate render-blocking resources or Properly size images.
  • Which element is the page's LCP: look for it in the Largest Contentful Paint element diagnostic.

Two tips: run Lighthouse in an incognito window (browser extensions distort the results) and repeat it two or three times, because results vary from one run to the next.

The Network tab

In Submitting Forms you used the Network tab to see form submissions. It's also the best way to see how the page loads:

  1. Open DevTools > Network and tick Disable cache, to simulate a first visit.
  2. In the throttling drop-down, which says No throttling by default, choose Slow 4G or 3G: this simulates a slow mobile connection.
  3. Reload the page.

Look at:

  • The Waterfall: one bar per resource, showing when it started and how long it took. Resources that start late, or that wait for others, are candidates for optimisation.
  • The Priority column (if it isn't shown, right-click the column headers and enable it): check what priority each image gets.
  • The bottom line: number of requests, data transferred and the DOMContentLoaded and Load times.
  • As you scroll down the page, the requests for the deferred images and frames appear at that moment.

For a finer analysis there's the Performance tab, which records the load frame by frame; it's beyond the scope of this course.

Project: a faster Blue Cup

  1. Measuring the starting point

Open gallery.html with Live Server in an incognito window and run Lighthouse, Performance category, mobile mode. Repeat with menu.html and news.html. Write down the metrics. Some plausible results at this point:

Page LCP LCP element CLS Main warnings
gallery.html 3.1 s The storefront (img inside picture) 0 Product images downloaded even though they aren't visible; the LCP image is discovered with low priority
menu.html 1.6 s The introductory paragraph 0 Nothing serious
news.html 1.8 s The first paragraph 0 Nothing serious

The exact numbers will depend on your computer and the weight of your images. What matters is the before-and-after comparison. CLS is 0 on all of them: that's the reward for having written width and height since Module 3.

Remember that with Live Server the "server" is on your own computer: there's no real latency or compression. Real measurements are done on the published site; what you're looking for here is to detect order and priority problems, which show up just the same.

  1. Scripts to external files with defer

Create the the-blue-cup/js/ folder and, inside it, three files. In each one, paste the code that is currently inside the corresponding script, without the <script> and </script> tags:

New file Code it contains Comes from
js/menu-filter.js The "Show gluten-free products only" filter menu.html, end of the main (Data Attributes)
js/chart.js The "Most ordered" bar chart news.html, end of the main (Graphics in HTML)
js/conditions.js Opening the conditions dialog bookings.html, end of the main (Other Semantic Elements)

For example, js/conditions.js ends up like this:

// Opens the booking conditions dialog (bookings.html)
const conditions = document.getElementById("conditions");
document.getElementById("open-conditions").addEventListener("click", () => conditions.showModal());
  • A .js file contains only JavaScript: no HTML tags.
  • The comment on the first line states what it does and which page uses it. Single-line JavaScript comments start with //.
  • The code doesn't change one bit.

Then delete the three <script>…</script> blocks at the end of the main and link each file in the head of its page, right after the stylesheet:

    <link rel="stylesheet" href="css/styles.css">
    <script src="js/menu-filter.js" defer></script>

In news.html, <script src="js/chart.js" defer></script>, and in bookings.html, <script src="js/conditions.js" defer></script>.

Why does it work without changing the code, if the script is now in the head, before the checkbox, the table, the canvas or the dialog exist? Thanks to defer: the script is downloaded while the browser reads the HTML, but it isn't run until the document is complete. When it runs, getElementById already finds all the elements. Without defer, the script would run immediately, getElementById would return null and the console would show an error.

Benefits of the change:

  • Performance: the scripts are discovered and downloaded from the start, in parallel, without blocking anything.
  • Caching: an external file is cached; code inside the HTML is downloaded again on every visit to the page.
  • Separation: the HTML goes back to containing only content and structure, as the review in HTML Best Practices required.
  • Validation: the .htmlhintrc from Validating HTML Code already allowed scripts in the head (head-script-disabled: false) in anticipation of this moment.

Check in Live Server that the filter, the chart and the dialog still work, and that the console shows no errors. If something fails, check the path (js/, not /js/) and that the defer attribute is there.

  1. Lazy loading and priority in gallery.html

The storefront is the first image and the page's LCP: it gets fetchpriority="high" and never loading="lazy". Add the attribute to the img in the picture (the source elements don't change):

            <img src="img/storefront.jpg"
                 alt="The Blue Cup's storefront with its blue awning and a terrace with four tables"
                 width="800" height="600" fetchpriority="high">

The three product photos are below the storefront: on mobile, several screens further down. Add loading="lazy" to each one:

              <img src="img/croissant-400.webp"
                   srcset="img/croissant-400.webp 400w, img/croissant-800.webp 800w"
                   sizes="(min-width: 64rem) 18rem, (min-width: 48rem) 30vw, (min-width: 30rem) 45vw, calc(100vw - 3.5rem)"
                   alt="Golden, flaky croissant on a white plate"
                   width="400" height="400" loading="lazy">

Do the same with the lemon sponge cake and the sourdough bread. The srcset and sizes stay as you left them in Module 9.

The video is already fine: preload="metadata" only downloads the basic data (duration, dimensions) and the poster; the full video is downloaded when you press play. The audio has preload="none". There's nothing to change.

  1. Checking the frames in contact.html and news.html

The OpenStreetMap map and the YouTube interview have had loading="lazy" since Using iframes. Check it in the code and in the Network tab: with a small window, the requests to openstreetmap.org and youtube-nocookie.com only appear when you scroll down to them.

  1. preconnect for external services

On each page that embeds an external service, add a connection hint to its domain in the head, next to the stylesheet:

In news.html:

    <link rel="preconnect" href="https://www.youtube-nocookie.com">

In contact.html:

    <link rel="preconnect" href="https://www.openstreetmap.org">
  • That way, when the person scrolls down to the video or the map and the deferred iframe starts loading, the connection to the service is already open and it appears sooner.
  • It goes only on the page that uses that service, and there's one per page: within the recommended limit.
  • The balance with loading="lazy": if the frame is a long way down and the person takes a while to get there, the browser may close the prepared connection before using it, and Lighthouse might warn about an unused preconnection. If you see this in your measurements, change preconnect to <link rel="dns-prefetch" href="…">, which is lighter and doesn't expire so quickly. At The Blue Cup, the map and the video are in the middle of their pages, and preconnect is reasonable.

  1. Updating the template

In template.html, add a comment in the head, right after the stylesheet, so that any new page follows the convention:

    <link rel="stylesheet" href="css/styles.css">
    <!-- The page's own scripts: <script src="js/name.js" defer></script> -->
    <!-- Embedded external services: <link rel="preconnect" href="https://domain"> -->

  1. Measuring again

Run Lighthouse again on the three pages. Plausible results:

Page LCP before LCP after Main change
gallery.html 3.1 s 2.1 s The storefront is requested with high priority from the start; the product photos no longer compete with it
menu.html 1.6 s 1.5 s Script downloaded in parallel
news.html 1.8 s 1.7 s Script downloaded in parallel

And in the Network tab, with Slow 4G and the cache disabled, check on gallery.html that:

  • The storefront appears at the start of the waterfall with High priority.
  • The product photos don't appear until you scroll down the page.
  • No script bar blocks the rest of the downloads.

Project status at the end of the module

File New in Module 10
.prettierrc and .htmlhintrc New, in the root: automatic formatting and checking as you type
template.html New: common skeleton (complete head, skip link, header without aria-current, main#content, footer) with CHANGE comments and the convention for scripts and preconnect; not published
All seven pages a.skip-link "Skip to content" link as the first child of the body; no outdated comments; formatted with Prettier; validation without errors
css/styles.css Section 2: .skip-link rules; section 8: ::placeholder with --color-text-muted and opacity: 1
index.html aside#offer with aria-labelledby="offer-title"; offer with "Was €4.20; now €3.50"
menu.html #filter-result with aria-live="polite"; script in js/menu-filter.js with defer in the head
bookings.html Hints with the id values help-phone, help-time, help-guests and help-comments, associated with aria-describedby; dialog with aria-labelledby="conditions-title"; script in js/conditions.js with defer
gallery.html Storefront with fetchpriority="high"; product photos with loading="lazy"; video track with kind="captions"
news.html Search button with type="submit"; aside#newsletter with aria-labelledby="newsletter-title"; script in js/chart.js with defer; preconnect to youtube-nocookie.com
contact.html No <br> after the message label; preconnect to openstreetmap.org
js/ New folder: menu-filter.js, chart.js, conditions.js

Pending items noted for Module 11: the real identifier of the interview video, the professional review of privacy.html, not publishing template.html and starting to version the CSS and JS files with ?v= after deployment.

Conventions established in the module: a best practices, validation and accessibility checklist before considering any page finished; Prettier on save, with two spaces; zero errors in the W3C validator; new pages created from template.html; an a.skip-link skip link to main#content; minimum contrast of 4.5:1 (3:1 for large text and components) measured with a tool; tabindex only 0 or -1; ARIA only when HTML isn't enough (aria-describedby with the help- prefix for field hints, aria-live="polite" for dynamic messages, aria-labelledby with the -title suffix to name regions and dialogs after their heading); videos with kind="captions" when the track includes sounds; JavaScript in js/, linked in the head with defer; loading="lazy" on images and frames outside the first screen and never on the LCP image, which gets fetchpriority="high"; a preconnect only on the page that uses the external service.

Common Mistakes and Tips

  • loading="lazy" on every image "just in case": if it reaches the main image, LCP gets worse. Only defer what's below the first screen.
  • Deferred images without width and height: they cause jumps when they arrive.
  • fetchpriority="high" on lots of images: if everything is a priority, nothing is.
  • defer or async on a script without src: they have no effect. Move the code into a file.
  • async on a script that needs the DOM or depends on another: it may run too early or in a different order. For page scripts, defer.
  • Writing /js/filter.js with a leading slash: it's a path from the root of the domain, which doesn't work when opening the files locally or if the site is published in a subfolder. Relative paths.
  • A preconnect to every domain imaginable: more than two or three is counterproductive.
  • Measuring only once, with a full cache and the best connection: the results won't look anything like your visitors'. Incognito, cache disabled, throttling and several runs.
  • Tip: before optimising, identify the LCP element of each page. Often, a single line on that image (removing a lazy, adding a fetchpriority) improves things more than anything else.

Exercises

Exercise 1. A page of The Blue Cup dedicated to the bread-making workshop has: a large photo of the workshop at the very top, some text, a gallery of twelve smaller photos, a YouTube video at the end and a script js/workshop-gallery.js that enlarges the photos when you click them. Write the attributes you would give each element (main photo, gallery photos, iframe, script) and the resource hints in the head, and justify each decision.

Exercise 2. State what will happen in each case, assuming both scripts are in the head and that menu.js uses a function defined in utilities.js:

a) <script src="js/utilities.js" defer></script> and <script src="js/menu.js" defer></script>. b) <script src="js/utilities.js" async></script> and <script src="js/menu.js" async></script>. c) <script src="js/utilities.js"></script> and <script src="js/menu.js"></script>, and menu.js looks for an element in the body with getElementById.

Exercise 3. When you run Lighthouse on a page, these diagnostics appear. Explain what they mean and what you would change in the HTML:

a) Largest Contentful Paint image was lazily loaded. b) Image elements do not have explicit width and height. c) Eliminate render-blocking resources: js/analytics.js.

Solutions

Solution 1.

<head>
  …
  <link rel="stylesheet" href="css/styles.css">
  <script src="js/workshop-gallery.js" defer></script>
  <link rel="preconnect" href="https://www.youtube-nocookie.com">
</head>
<body>
  …
  <img src="img/workshop-800.webp" alt="…" width="800" height="600" fetchpriority="high">
  …
  <img src="img/workshop-01-400.webp" alt="…" width="400" height="300" loading="lazy">
  <!-- … the other eleven photos, the same … -->
  …
  <iframe src="https://www.youtube-nocookie.com/embed/…" title="Video: …" width="560" height="315" loading="lazy" allow="…"></iframe>
</body>
  • Main photo: it's the LCP. fetchpriority="high" and no lazy. With width and height.
  • Gallery: it's below the text; twelve photos would compete with the main one. loading="lazy", with width and height to avoid jumps. (If on desktop the first photos in the gallery were visible on load, you could leave the first row without lazy; if in doubt, measure.)
  • iframe: at the end of the page; loading="lazy", as well as title, size and a minimal allow (Using iframes).
  • Script: it needs the DOM (the photos) and isn't urgent: an external file with defer in the head.
  • preconnect to YouTube: a single external domain on the page. As the video is at the end, dns-prefetch would also be a reasonable option; you decide by measuring.

Solution 2.

a) It works: both are downloaded in parallel without blocking and run in order, once the HTML is complete. When menu.js runs, utilities.js has already run. b) It may fail intermittently: each one runs as soon as it's downloaded. If menu.js arrives first, the function from utilities.js doesn't exist yet and an error occurs. And since they run as soon as they arrive, the element in the body may not exist yet either. Intermittent errors are the hardest to track down. c) Both block parsing (the page takes longer to appear) and run in order, so the function exists; but when menu.js runs, the browser hasn't read the body yet: getElementById returns null and an error occurs. The solution is to add defer to both.

Solution 3.

a) The image that is the LCP has loading="lazy": the browser requests it late. Remove loading="lazy" from that image and add fetchpriority="high". b) There are images without width and height: they cause layout shifts (CLS) on load. Add their real dimensions in pixels (and keep max-width: 100% and height: auto in the CSS). c) The script js/analytics.js is in the head without defer or async and blocks painting. As an analytics script is independent of everything else and of the DOM, async is appropriate; if it depended on the DOM, defer.

Conclusion

You've learnt why performance matters and how it's measured with the Core Web Vitals (LCP, CLS and INP), and how the browser loads a page: HTML is parsed in order, CSS blocks painting and a normal script blocks parsing. You know how to defer images and frames with loading="lazy" (never on the main image), prioritise the LCP with fetchpriority="high", load scripts without blocking using defer (or async for independent ones), set up connections early with preconnect and dns-prefetch or download critical resources with preload, and you know in passing about decoding, modules, minification, compression and versioning with ?v=. You've also learnt to measure with Lighthouse and with the Network tab using throttling. With this lesson you complete the Best Practices and Accessibility module. Over the course of the module, The Blue Cup has been through a complete professional review: it has a checklist, a base template and consistent formatting; it passes the W3C validator without errors; it has a link to skip to the content, a palette with verified contrast, associated form hints, announced dynamic messages and named regions; it has passed both an automated and a manual accessibility audit; and now its scripts live in js/ with defer, the gallery's main image arrives first and whatever isn't visible waits its turn. The site doesn't just work: it's built properly. All that's left is the most exciting part: bringing it all together and putting it online. In the next and final module, Project: Building a Complete Website, you'll start with the lesson Planning Your Website, review the whole site with a project mindset, tie up the loose ends you've been noting down and get it ready to publish on a real server.

HTML Course

Module 1: Introduction to HTML

Module 2: Text Formatting in HTML

Module 3: Links and Media in HTML

Module 4: Tables in HTML

Module 5: Forms in HTML

Module 6: HTML5 Semantic Elements

Module 7: Advanced HTML Techniques

Module 8: Integrating HTML and CSS

Module 9: Responsive Web Design

Module 10: Best Practices and Accessibility

Module 11: Project: Building a Complete Website

© Copyright 2026. All rights reserved