html 插入script,HTML中的script标签研究

Script 的堵塞(block)特性

Scripts without async or defer attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page. - MDN

the blocking nature of JavaScript, which is to say that nothing else can happen while JavaScript code is being executed. In fact, most browsers use a single process for both user interface (UI) updates and JavaScript execution, so only one can happen at any given moment in time. The longer JavaScript takes to execute, the longer it takes before the browser is free to respond to user input. - Nicholas C. Zakas「High Performance JavaScript 」

上面引用两段话的意思大致是,当浏览器解析DOM文档时,一旦遇到 script 标签(没有defer 和 async 属性)就会立即下载并执行,与此同时浏览器对文档的解析将会停止,直到 script 代码执行完成。出现这种堵塞行为一方面是因为浏览器的UI渲染,交互行为等都是单线程操作,另一方是因为 script 里面的代码可能会影响到后面文档的解析,比如下面的代码:

html

document.write("The date is " + (new Date()).toDateString());

这个堵塞特性会严重的影响用户体验,下面是几种优化方案:

尽量把脚本往文档的后面放,以减少对文档的堵塞,最好放在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值