Comments (3)
defer 与 async
- async模式 <script type="text/javascript" src="x.min.js" async="async"></script>
当浏览器遇到script标签时,文档的解析不会停止,其他线程将下载脚本,脚本下载完成后开始执行脚本,脚本执行的过程中文档将停止解析,直到脚本执行完毕。 - defer模式 <script type="text/javascript" src="x.min.js" defer="defer"></script>
当浏览器遇到 script 标签时,文档的解析不会停止,其他线程将下载脚本,待到文档解析完成,脚本才会执行。 - 总结
所以async和defer的最主要的区别就是async是异步下载并立即执行,然后文档继续解析,defer是异步加载后解析文档,然后再执行脚本。主要的参考是如果脚本不依赖于任何脚本,并不被任何脚本依赖,那么则使用 defer,如果脚本是模块化的,不依赖于任何脚本,那么则使用 async。
from cqupt-yifanwu.github.io.
关于javascript优化
- 在启动期间,JavaScript 引擎花费 显著 的时间来解析、编译和执行脚本。这一阶段很关键,因为如果它用时太多,将会 延后 用户可以与我们的网站 互动 的时间点。想象一下,如果用户可以看到一个按钮,但很多秒之后才能点击或触摸,这将会 降低 用户体验。桌面端本就缓慢的解析、编译过程,在一般手机上则需要更长的时间。
- 我们做些什么可以减少javascript的解析时间呢?
1.传输更少的 JavaScript。 需要解析的脚本越少,我们在解析和编译阶段用的时间就越少。
2.使用 code-splitting 技术,只发送用户当前路由需要的代码,延迟加载其余代码。 想要避免解析太多的 JS,这可能是最有帮助的方法。
3.Script streaming: 过去,V8 已经告诉开发者通过 async/defer 选择使用 Script streaming 模式,可以使得解析时间减少 10 - 20%。这允许 HTML 解析器能够至少先检测到资源,将(解析)工作分配给 script streaming 线程,从而不阻塞文档解析。现在,解析器阻塞脚本也有了个模式,不需要做什么额外操作。V8 建议 先加载较大的打包文件,因只有一个脚本流线程
4.测量依赖的解析成本 ,比如各种库和框架。在可能的情况下,将它们切换为拥有更快解析速度的依赖(例如,把 React 切换为 Preact 或 Inferno,后两者启动时需要更少的字节码,更少的解析、编译时间)。
from cqupt-yifanwu.github.io.
react 中性能优化
- node同构直出
- 利用webpack的codeSplting
对js优化的补充
- 对计算量较大的部分使用web worker
- 对scroll || resize 等事件进行节流和消抖
- 减少对DOM的访问(变量缓存)
- 对复杂的计算且出现次数较多的进行变量缓存
- 减少使用eval()和with()等方法,因为会欺骗词法作用域,引擎无法在编译时对作用域进行优化
- 使用事件委托,减少元素和事件处理函数之间的引用关系,当删除元素时要接触事件柄的绑定
from cqupt-yifanwu.github.io.
Related Issues (20)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cqupt-yifanwu.github.io.