Angular 技术问题:如何在跳转到页面前完成图片加载?
问题描述
我已在导航操作前添加1500ms延迟(配合SweetAlert成功弹窗),但跳转到首页后,页面中的图片仍需要很长时间才能加载完成。
相关代码
TypeScript 导航逻辑
navigate(name:string,title:string) { Swal.fire({ position: 'center', icon: 'success', title: `You go to the page ${title}`, showConfirmButton: false, timer: 1500, }) setTimeout(() => { this.router.navigate([`${name}`]); }, 1500); }
导航按钮 HTML
<div class="home-container"> <li (click)="navigate('home','Home')"> <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="house" class="svg-inline--fa fa-house " role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" color="#4d4d4e"> <path fill="currentColor" d="M575.8 255.5c0 18-15 32.1-32 32.1h-32l.7 160.2c0 2.7-.2 5.4-.5 8.1V472c0 22.1-17.9 40-40 40H456c-1.1 0-2.2 0-3.3-.1c-1.4 .1-2.8 .1-4.2 .1H416 392c-22.1 0-40-17.9-40-40V448 384c0-17.7-14.3-32-32-32H256c-17.7 0-32 14.3-32 32v64 24c0 22.1-17.9 40-40 40H160 128.1c-1.5 0-3-.1-4.5-.2c-1.2 .1-2.4 .2-3.6 .2H104c-22.1 0-40-17.9-40-40V360c0-.9 0-1.9 .1-2.8V287.6H32c-18 0-32-14-32-32.1c0-9 3-17 10-24L266.4 8c7-7 15-8 22-8s15 2 21 7L564.8 231.5c8 7 12 15 11 24z"> </path> </svg> <span class="home">Home</span> </li> </div>
首页图片 HTML
<img class="mor-image" src="../../assets/images/Mor.png" alt="mor">
解决方案
1. 提前预加载图片
在导航触发时或应用初始化阶段预加载图片,让浏览器缓存资源,跳转后直接从缓存读取:
navigate(name:string,title:string) { // 仅跳转首页时预加载目标图片 if (name === 'home') { const preloadImg = new Image(); preloadImg.src = '../../assets/images/Mor.png'; } Swal.fire({ position: 'center', icon: 'success', title: `You go to the page ${title}`, showConfirmButton: false, timer: 1500, }) setTimeout(() => { this.router.navigate([`${name}`]); }, 1500); }
也可在AppComponent的ngOnInit中预加载所有关键页面的图片:
ngOnInit() { const preloadList = [ '../../assets/images/Mor.png' // 其他需预加载的图片路径 ]; preloadList.forEach(src => { const img = new Image(); img.src = src; }); }
2. 优化图片资源体积
图片过大是加载慢的核心原因,可通过以下方式优化:
- 压缩图片:使用TinyPNG、Squoosh等工具压缩图片,在不损失画质的前提下减小文件体积。
- 改用现代格式:将图片转为WebP/AVIF格式,相同质量下体积更小,同时添加兼容性回退:
<picture> <source srcset="../../assets/images/Mor.webp" type="image/webp"> <img class="mor-image" src="../../assets/images/Mor.png" alt="mor"> </picture>
3. 配置Angular路由预加载
若首页为独立模块,可配置路由预加载策略,让应用在空闲时预加载首页模块的所有资源:
import { PreloadAllModules } from '@angular/router'; @NgModule({ imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })], exports: [RouterModule] }) export class AppRoutingModule { }
也可自定义预加载策略,仅预加载首页模块,避免不必要的资源消耗。
4. 添加图片占位符
为图片添加占位符,提升用户体验,避免页面加载时出现空白区域:
<!-- 纯色占位符 --> <img class="mor-image" src="../../assets/images/Mor.png" alt="mor" style="background-color: #f0f0f0;"> <!-- 低质量模糊占位图 --> <img class="mor-image" src="../../assets/images/Mor-placeholder.png" data-src="../../assets/images/Mor.png" alt="mor" (load)="this.src = this.dataset.src">
内容的提问来源于stack exchange,提问作者Mor levi
相关产品推荐
相关产品推荐

