Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in / Register
Toggle navigation
Y
yifu-study-front-share
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
CI / CD
CI / CD
Pipelines
Schedules
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Open sidebar
yifu-study
front
yifu-study-front-share
Commits
bb568db7
Commit
bb568db7
authored
May 07, 2022
by
刘磊
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
分享webpack性能优化
parent
46196f14
Pipeline
#15845
failed with stage
Changes
1
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
56 additions
and
0 deletions
+56
-0
preload和prefetch优化性能.md
source/_posts/preload和prefetch优化性能.md
+56
-0
No files found.
source/_posts/preload和prefetch优化性能.md
0 → 100644
View file @
bb568db7
---
title
:
性能优化---Preload&Prefetch
date
:
2022/5/7 14:06:20
tags
:
-
前端
-
盒子模型
-
CSS
author
:
刘磊
---
# 性能优化---Preload&Prefetch
在preload和prefetch之前,我们一般根据编码需求通过link或者script标签引入页面渲染和交互所依赖的js和css等;然后这些资源由浏览器决定优先级进行加载、解析、渲染等。
然而,有些情况我们需要某些依赖在浏览器进入渲染的主进程之前就希望被加载,但是实际资源加载的状况并不受我们控制,而是根据浏览器内部决定资源的优先级等状况进行加载的。即使我们将需要的资源按照希望的那样放在期望的位置,但是由于资源的加载和解析,尤其是js的加载、解析和编译是阻塞式的,因此往往还是达不到预期。或者,有些资源是我们后边需要的,我们希望在需要它的时候在进行解析和执行,并不想让它的加载影响其他资源的加载及首屏渲染时间。
preload和prefetch的出现为我们提供了可以更加细粒度地控制浏览器加载资源的方法。
```
<link ref='preload'>
<link ref='prefetch'>
```
#### preload特点
-
preload加载的资源是在浏览器渲染机制之前进行处理的,并且不会阻塞onload事件;
-
preload可以支持加载多种类型的资源,并且可以加载跨域资源;
-
preload加载的js脚本其加载和执行的过程是分离的。即preload会预加载相应的脚本代码,待到需要时自行调用;
#### prefetch特点
-
prefetch加载的资源可以获取非当前页面所需要的资源,并且将其放入缓存至少5分钟(无论资源是否可以缓存);并且,当页面跳转时,未完成的prefetch请求不会被中断;
#### preload和prefetch对比
-
preload主要用于预加载当前页面需要的资源;而prefetch主要用于加载将来页面可能需要的资源;
-
不论资源是否可以缓存,prefecth会存储在net-stack cache中至少5分钟;
-
preload需要使用as属性指定特定的资源类型以便浏览器为其分配一定的优先级,并能够正确加载资源;
## webpack中的perload和perfetch
问题:异步加载模块是Webpack官方所希望开发者实现的,而且异步加载也能提升首页加载速度,但是又会导致异步加载的那部分代码逻辑迟迟不能执行,可能导致用户的交互长时间没有响应。
所谓预取,就是提前获取将来可能会用到的资源。prefetch chunk会在父chunk加载完成之后进行加载。
那么该怎么做呢?我们要通过一种称作Magic Comment(魔法注释)的方式,让Webpack输出"resource hint(资源提示)",来告知浏览器。
```
document.getElementById('btn').onclick = function () {
import( /* webpackChunkName: 'base',webpackPrefetch:true*/ './base').then(({
mul
}) => {
console.log(mul(40, 3));
}).catch((err) => {
console.log(`base.js加载失败:${err}`);
});
}
```
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment