3
Chapter 3
Optimizing Fonts and Images
In the previous chapter, you learned how to style your Qwik application. Let's continue working on your home page by adding a custom font and a hero image.
In this chapter...
Here are the topics we will cover:
Different ways to add custom fonts
Different ways to add images
How Qwik optimizes the loading of fonts and images to improve performance and user experience
Why Optimize Fonts?
Fonts play a crucial role in web design, but using custom fonts can impact performance since these fonts need to be downloaded on a visitor’s first visit to a site.
Cumulative Layout Shift (CLS) is a metric used by Google to assess performance and user experience. With fonts, CLS can occur when the browser initially renders text with a fallback or system font, and then replaces it with a custom font once loaded. This change can affect the size, spacing, or layout of the text, influencing other elements on the page.
In Qwik, you can optimize font loading by using the `font-display`
property to control how fonts are loaded. Common values for this property include `swap`
and `fallback`
, allowing you to choose between different loading strategies.
To further improve performance, Qwik recommends self-hosting your fonts. Instead of using third-party providers like Google Fonts, you can download the font files and serve them from your own domain, which reduces network requests and enhances privacy as well as performance, especially in PWA scenarios or under limited connectivity.
This ensures that the custom font is used efficiently, minimizing impacts on CLS and enhancing the overall user experience.
A sudden shift in layout makes the user confirm a large order they intended to cancel.
It’s time to take a quiz!
Test your knowledge and see what you’ve just learned.
Why is it recommended to self-host fonts in a Qwik application?
What is Cumulative Layout Shift (CLS) and how can self-hosting fonts help to minimize it?
What is the effect of using the font-display property in Qwik?
Google Fonts
Google Fonts is a popular open source library, offering over 1500 font families.
While they are easy to use, they involve downloading a CSS file and fonts from different domains, causing a noticeable delay and switch in font loading despite using swap
.
Here's what happens:
- 1.The browser spots the
<link href="https://fonts.googleapis.com/css2">
tag, which prompts it to request a CSS file. - 2. After analyzing the file, it realizes a web font from
https://fonts.gstatic.com
is needed, leading to another request.
To mitigate this, we can self host our fonts.
Self Hosting
Rather than using a third-party provider like Google Fonts, we can self-host our fonts. This means we download the font files and serve them from our own domain.
Some benefits include:
- Improved performance
- More privacy as Google tracks font usage.
- Self-hosted fonts load offline, useful for PWA's or low connectivity situations.
Fontsource
Self-hosting with fontsourceis as easy as an npm install. It includes all of the google fonts, as well as other open source fonts, without the hassle of managing the files yourself.
Adding a primary font with Fontsource
To add a custom font to your Qwik application, you need to download the font files and add them to your project.
For your dashboard, let's use the variable version of the `Inter`
font by Fontsource.
First, install @fontsource-variable/inter:
Next, use the font in your src/global.css
file, you choose 'Advanced Usage' and copy the font-face declaration:
Now, you can use the `Inter`
font in your Qwik application.
To use the font in your CSS, you can reference the font family in your styles:
By adding `Inter`
to the <body>
element, the font will be applied throughout your application. Here, you're also adding `-webkit-font-smoothing`
and `-moz-osx-font-smoothing`
to ensure the font looks crisp on different browsers. It's not necessary to use this class, but it adds a nice touch.
Navigate to your browser, open dev tools and select the <body>
element. You should see Inter
are now applied under styles.
Add a second font by hosting it in your project
You can also host font files directly on our application.
Now it's your turn! Import a secondary font called `Lusitana`
by hosting the font files in your project. You must pass the font files to the src/global.css
file with the font-face declaration, and create a `.lusitana`
class in your CSS file to apply the font to specific elements.
Add your class to the <p>
element in your src/routes/index.tsx/
file.
For this practice, you use the Google Webfonts Helper, which is a tool that allows you to download the optimized google fonts.
You must take the two font-weight (regular, 700) files and add them to your project.
Hints:
- In Google Webfonts Helper/lusitana check the 700 box.
- You can customize folder prefix to adjust your
@font-face
declaration. (e.g."./assets/fonts/"
)- Don't forget copy the font-face declaration and add it to your
src/global.css
file.- Download the font zip files, extract them and add the two fonts files to your project.
- Create a
/fonts
folder intosrc/assets/
directory and add the font files there.
Finally, the <LRDQwikLogo />
component also uses Lusitana. It was commented out to prevent errors.
You can download it here:
Add the LRDQwikLogo.tsx
file to your src/assets/svg/
folder.
In your src/routes/index.tsx
file, uncomment the import and the<LRDQwikLogo />
component.
Now, if you run your application, you should see the `Lusitana`
font applied to your <p>
and the icon in your <LRDQwikLogo />
component.🏆
Congratulations! You have successfully added custom fonts to your Qwik application.🎉
Why optimize images?
In Qwik, optimizing images is crucial for reducing file sizes and improving loading performance on networks, especially mobile ones. Qwik integrates this functionality through the vite-imagetools module, allowing automated management without the need for additional packages.
How does it work with Qwik?
- 1.Importing images: You can import an image from the
src
folder. This image is automatically converted into multiple formats (WebP, AVIF) and sizes (200px, 400px, 600px, 800px, 1200px) suitable for different breakpoints. - 2.Rendering the
<img>
Element: An<img>
element is generated with thesrcset
attribute to specify different image sources depending on the resolution used by the browser. This allows the most appropriate image to be loaded depending on the device's resolution. - 3.Image Attributes: Images are loaded lazily (
loading="lazy"
) and asynchronous decoding (decoding="async"
) is used to not block the page's rendering while the image is being decoded. - 4.Suffix: Add the
?jsx
suffix at the end of the image path to enable image optimization.
Adding the desktop hero image
Let's add a hero image to your dashboard. This image will be displayed on larger screens.
First download the hero desktop image here:
In your src/assets/
folder, create a new folder called img
and add the hero image there.
In your src/routes/index.tsx
file, import the hero image, don't forget to add the ?jsx
suffix at the end of the image path.
Next, add the hero image to your file:
⚠️ The 'hidden md:block'
class ensures the image is only displayed on larger screens.
This is what your home page should look like now:
Practice: Adding the mobile hero image
Now it's your turn! Add a mobile hero image to your dashboard. This is the image that will be displayed on smaller screens.
You can download the hero mobile image here:
Once you're ready, expand the code snippet below to see the solution.
Great! Your home page now has a custom font and hero images.
It’s time to take a quiz!
Test your knowledge and see what you’ve just learned.
Using the .jsx suffix when importing images in Qwik enables automatic optimization, including conversion to modern formats and lazy loading of images.
Recommended reading
Continue your exploration of these important topics with the following selected resources for additional depth:
Source code
You can find the source code for chapter 3 on GitHub.
📺 Chapter 3 Video Walkthrough
Watch RumNCode 🥃 build out the third chapter with clear explanations and real-time coding. This chapter is presented by RumNCode 🥃, a Qwik Hero from the official Discord community.
You've Completed Chapter 3
You've learned how to use fonts and images using Qwik.
Next Up
4: Creating Layouts and Pages
Let's create your dashboard routes using nested layouts and pages!
https://github.com/DevWeb13/learn-qwik/issues/23