加载图像
问题描述:
之前渲染阻止脚本我有以下结构的网页:加载图像
<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
答
常见的形式给出延迟图片加载会是这样的:
$(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>
尝试'onload'事件 –
[脚本已经被加载之前执行的加载的图像可以开始。](https://stackoverflow.com/questions/28635141/sequence-in-which-html-page-loads)至少这是浏览器应该做的。 –
这里有一个关于同一主题的讨论https://stackoverflow.com/questions/2703468/is-it-possible-to-run-javascript-before-any-image-loads – msoliman