外部样式 & 外部脚本->加载&阻塞

本文探讨了外部样式(CSS)与脚本(JS)在网页加载过程中的交互作用,指出CSS会阻塞后续JS执行,直至样式加载完成。通过不同场景测试,包括同步与异步脚本加载,揭示了最佳实践:将脚本置于CSS前,或将CSS内联,以优化网页渲染速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

webkit & Gecko

就Webkit 和 Gecko 来讲,主要的渲染流程大体一样
在这里插入图片描述
测试结果:

外部样式会阻塞后续脚本执行,直到外部样式加载并解析完毕

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script>var start = +new Date;</script>
  <link href="http://udacity-crp.herokuapp.com/style.css?rtt=2" rel="stylesheet">
  
</head>
  
<body>
  <script>
    var end = +new Date;
    alert(end-start); //
  </script>
</body>
</html>

在这里插入图片描述
外部样式不会阻塞后续外部脚本的加载,但会阻塞外部脚本的执行

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script>var start = +new Date;</script>
  <link href="http://udacity-crp.herokuapp.com/style.css?rtt=2" rel="stylesheet">
  
</head>
  
<body>
  <script src="http://udacity-crp.herokuapp.com/time.js?rtt=1&a"></script>
  <div id="result"></div>
  <script>var end = +new Date;console.log(end-start);</script>
  
</body>
</html>

在这里插入图片描述
如果后续外部脚本含有async属性(IE下为defer),则外部样式不会阻塞该脚本的加载与执行

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script>var start = +new Date;</script>
  <link href="http://udacity-crp.herokuapp.com/style.css?rtt=2" rel="stylesheet">
  
</head>
  
<body>
  <script src="http://udacity-crp.herokuapp.com/time.js?rtt=1&a" async></script>
  <script>var end = +new Date;console.log(end-start);</script>
</body>
</html>

在这里插入图片描述
建议:
1、脚本应该放在外部css的前面,不论脚本是内联还是外部(当然,最好是脚本放在body的最后面);
2、可以的话,外部css最好直接内联到页面。

有关于一些其他的详细内容不加以解析,请看相关资料!

参考资料:
http://velocity.oreilly.com.cn/2010/ppts/limufromTaobao.pdf
http://lifesinger.wordpress.com/
http://hikejun.com/blog/2012/02/02/js和css的顺序关系/
http://www.html5rocks.com/zh/tutorials/internals/howbrowserswork/
http://www.2cto.com/kf/201406/305852.html
http://www.w3cmm.com/dom/document-stylesheets-getstylesheet.html
https://www.cnblogs.com/dojo-lzz/p/3983335.html
https://www.xuecaijie.com/htmlcss/172.htm

其他相关资料:
十分钟读懂浏览器渲染流程
浅析浏览器渲染原理
我的小树林

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值