Loading Optimization
🎯 Introduction
The first thing users notice when opening a page is loading speed. Images that take too long to appear or a blank screen lasting several seconds may make them leave. Fortunately, many loading problems improve considerably with a few common techniques, without advanced technology.
By the end of this article, you will be able to:
- Lazy load images with the native
loading="lazy"attribute and understand how to implement the same idea with IntersectionObserver. - Lazy load routes with dynamic
import()and explain how code is split at build time and downloaded on navigation. - Distinguish
preloadfromprefetchand choose the right use case for each. - Understand the principle behind code splitting: code that the initial view does not need should not delay it.
🧱 Lazy Loading Images: loading="lazy"
Consider an article with dozens of illustrations. Only one or two are visible when the page opens. Downloading every image immediately can delay the initial view and waste bandwidth on content users may never scroll to.
Lazy loading defers an image's download until it approaches the viewport. This used to require substantial JavaScript, but browsers now support it natively through a single img attribute:
<!-- Load images in the initial viewport normally -->
<img src="banner.png" alt="Top banner" />
<!-- Add loading="lazy" to images outside the initial viewport -->
<img src="photo-1.png" alt="Illustration 1" loading="lazy" />
<img src="photo-2.png" alt="Illustration 2" loading="lazy" />
The browser checks the image's distance from the viewport and starts downloading as it approaches. With broad support and no extra implementation work, this is the preferred approach to lazy loading images.
loading="lazy" to images visible immediately, such as the top banner. It may defer their downloads and slow the initial view.🧱 Lazy Loading Images: The IntersectionObserver Approach
Native support is convenient, but understanding a manual implementation is still useful. It often comes up in interviews, and triggering work when an element enters the viewport also applies to infinite scrolling and impression tracking.
The key browser API is IntersectionObserver. Think of it as a watcher: ask it to observe an element, and it notifies you when that element enters or leaves the viewport. Use that notification to assign the image's real URL:
<!-- Leave src unset or use a placeholder; store the real URL in data-src -->
<img class="lazy-img" data-src="photo-1.png" alt="Illustration 1" />
// Create an observer for all .lazy-img elements
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
// isIntersecting is true when the element intersects the viewport
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // Set the real URL to start downloading
observer.unobserve(img); // Stop observing once loading has been initiated
}
});
});
document.querySelectorAll('.lazy-img').forEach((img) => {
observer.observe(img); // Start observing each image
});
The process has three steps: store the real URL in data-src → detect the image entering the viewport → assign the URL to src to start downloading. Native loading="lazy" is usually sufficient; understand the manual approach without needing to use it everywhere.
🧱 Lazy Loading Routes
Lazy loading applies to entire pages as well as images. A Vue single-page application might have a dozen routes. Bundling them into one JavaScript file forces users to download all their code just to open the home page, slowing the initial view.
With route lazy loading, the route configuration uses a function returning import() instead of importing the component directly:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
// Import the home page directly because the initial view needs it
{ path: '/', component: Home },
// Dynamically import other pages only when their routes are visited
{ path: '/about', component: () => import('./views/About.vue') },
{ path: '/user', component: () => import('./views/User.vue') },
],
});
The key is () => import('./views/About.vue'). Both webpack and Vite recognize dynamic import() and split About.vue into a separate file instead of including it in the main bundle. At runtime, the browser downloads the About page's code only when the user visits /about.
The home page therefore downloads only shared code and its own code. A smaller download makes the initial view faster. Keep the home page directly imported when it is needed immediately.
⚡ Preload and Prefetch
Lazy loading postpones resources that are not needed yet. Two complementary techniques prepare resources in advance: preload and prefetch. Both use <link rel>, and their similar names make them easy to confuse. Let's compare them.
preload: start downloading a resource needed soon by the current page, with high priority.
For example, a large heading uses a custom font. Without a hint, the browser discovers that font only after parsing CSS, so the heading may first appear in a fallback font and then change. Preloading starts the download earlier:
<head>
<!-- Download a resource needed immediately for the current page with high priority -->
<link rel="preload" href="/fonts/title.woff2" as="font" type="font/woff2" crossorigin />
</head>
The as attribute is required. It specifies the resource type, such as font, script, style, or image, so the browser can assign priority and reuse the downloaded resource correctly.
prefetch: download a resource that a future page may need, with low priority during idle time.
For example, a user browsing a product list is likely to open a detail page next. After the current page loads and the network is idle, the browser can download that page's code in advance, making the next navigation feel instant:
<head>
<!-- Use idle time to download a likely next-page resource with low priority -->
<link rel="prefetch" href="/js/detail-page.js" />
</head>
Remember the difference:
| Comparison | preload | prefetch |
|---|---|---|
| Target | Resources for the current page | Resources for the next page |
| Priority | High; download starts immediately | Low; download during idle time after the current page loads |
| Typical uses | Initial-view fonts, critical CSS/JavaScript | Code for a likely next navigation |
You can inspect the timing and priority of both types in the Chrome DevTools Network panel.
🧱 Code Splitting
Let's step back and examine the shared idea behind these techniques: code splitting.
Bundlers normally combine code into a small number of files. That works for small projects, but as a project grows, the main bundle expands and the initial view must download and parse more code. Splitting divides code by when it is needed: keep initial-view code in the main bundle and load other code on demand.
We have already seen two related examples. Route lazy loading splits code by route, with each import() defining a split point. Prefetch often downloads those asynchronous chunks ahead of time. Another common approach splits by dependency, placing rarely changed libraries such as vue and vue-router in separate files so they can remain cached when application code changes.
manualChunks and webpack's splitChunks, belongs to the build tools. See the Vite course and Webpack course. Here, focus on the principle of splitting code according to need.Use a simple test: does the initial view need this module? If not—for example, an admin chart page or a complex editor inside a dialog—split it out and load it on demand.
❓ Questions and Answers
Q1: Do all browsers support loading="lazy"?
Recent versions of major browsers, including Chrome, Firefox, Safari, and Edge, support it. Older browsers ignore the attribute and load images immediately. The functionality still works, without the lazy loading benefit.
Q2: Does route lazy loading defer all of a component's code until navigation?
Yes. The component and its exclusive dependencies go into its separate chunk. If a module is also used by the main bundle or another lazy route, the bundler typically extracts it into shared code to avoid duplicate downloads.
Q3: Can preload and prefetch be used together?
Yes. They target different resources: preload for current-page critical resources, prefetch for a future page. Watch the total number of hints, though. Too many advance downloads consume bandwidth and can delay more important resources.
Q4: Why does preload require as?
It tells the browser the resource type so it can assign the correct priority and reuse the download when the resource is consumed. Omitting it can lead to duplicate downloads and defeat the purpose of preloading.
Q5: How do route lazy loading and prefetch relate?
They complement each other. Lazy loading decides to split code and defer downloading until needed. Prefetch downloads that split code earlier during idle time. Frameworks such as Nuxt can automatically provide route prefetching so lazy-loaded pages still open quickly.
🧪 Exercises
Exercise 1: Add lazy loading to a route configuration. The following code imports User.vue directly. Change it so the component loads only when its route is visited:
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import User from './views/User.vue';
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
// Write your code here: lazy load the User route
{ path: '/user', component: User },
],
});
Exercise 2: A page uses the custom font /fonts/title.woff2 for its large heading. Users are also likely to visit the About page next, whose code is in /js/about-page.js. Add suitable <link> hints to <head>, choosing the correct rel and priority:
<head>
<!-- Write your code here: preload the font used in the initial viewport -->
<!-- Write your code here: prefetch the About page's code -->
</head>
Why do the two resources use different rel values? What would happen if you swapped them?
🎉 You now have the tools to optimize loading! Next, we will explore rendering optimization and make the page run smoothly after its resources have loaded.
