[读书笔记]高性能JS-加载执行

本文探讨了网页加载过程中遇到的问题,如UI更新阻塞,并提出了几种优化策略:将JS放置在</body>标签前,合并脚本减少HTTP请求,使用非阻塞JS加载以及动态脚本加载技术。详细介绍了如何利用async属性和动态创建script元素来实现异步加载,以及跨浏览器兼容性的解决方案。

for web browser have only one thread.while loading or execute js, the UI update will be blocked.some way to improve

1.put js before </body> tag.so js will be loaded and run after page have been fully loaded.

2.orangize script.combine some script to one to reduce HTTP request.

3 no blocked js. loading js after window.onload run or DOMContentedloaded run.

4 ***dynamic script

use async script 

some tip http://stackoverflow.com/questions/33470619/why-script-dom-element-can-be-async-loading/33471838#33471838

var script=document.createElement('script');

script.src='aa.js';

document.getElementByTagName('head')[0].appendChild(script);

this way, js will run as soon as loaded.if js need other api,we need to make sure api is run before this js code. so sequence of script is important.

for w3c.we use one of attribute of script,onload to test if script has fully loaded.

script.onload=function(){

  alert('loaded');

}

but for IE, we use readystatechange event;

it has 4 state, state loaded and state4 complete important.

but not sure which will happen first.if one of two happened,means script fully loaded.one of state run ,we cancel the event;we use

script.onreadystatechange=function(){

if(script.readyState==='complete' || script.readyState==='loaded'){

  script.onreadystatechange=null;

  alert('loaded');

}

}

and combine two to one can make cross browser version.

转载于:https://www.cnblogs.com/wz0107/p/4960127.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值