在图像之前加载渲染阻止脚本

时间:2017-10-21 06:36:28

标签: javascript html5 browser

我有一个具有以下结构的页面:

<html>
  <head>
    <script type="text/javascript" src="//example.com/s1.min.js"></script>
    <script type="text/javascript" src="//example.com/s2.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
  </head>
  <body>
    ... template initiation, layout, etc. ...
    <ul>
      <li><img src="https://cdn.example.com/img1.jpg"/></li>
      <li><img src="https://cdn.example.com/img2.jpg"/></li>
      <li><img src="https://cdn.example.com/img3.jpg"/></li>
      ... and a lot more images ...
    </ul>
    ... a bunch of scripts here ...
  </body>
</html>

当我使用Chrome devtool模拟慢速连接时,页面空白最多1分钟,因为头部的jquery脚本阻止了DOM。该脚本需要很长时间才能加载,因为Chrome会在脚本的同时下载图像,从而使带宽饱和。

我不明白这种行为。我认为头部中的渲染阻塞脚本首先被下载到正文中的其他内容之前?测试证据证明不然。

我无法轻易地将jquery移动到页面底部或使其异步,因为它可能会破坏我不拥有的页面中的其他脚本。

我已经看过很多关于删除渲染阻止脚本的讨论。但我的问题更多的是为什么渲染阻止脚本没有获得'优先'下载?如果我有什么办法可以保证下载32KB脚本,那么在网络被图像下载饱和之前就加载了DOM?

编辑: 这是时间线图。请注意如何首先请求jquery,但不阻止图像。 timeline graph

1 个答案:

答案 0 :(得分:0)

延迟加载图像的常见方法是这样的:

$(function(){
  $('img[data-src]').each(function(){
    if(!this.src) this.src = this.dataset.src;
    delete this.dataset.src;
  })
  //just to show the resulting markup, as the image-urls are just placeholder
  console.log($('ul').html());
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
... template initiation, layout, etc. ...
<ul>
  <li><img data-src="https://cdn.example.com/img1.jpg" /></li>
  <li><img data-src="https://cdn.example.com/img2.jpg" /></li>
  <li><img data-src="https://cdn.example.com/img3.jpg" /></li>
  ... and a lot more images ...
</ul>