我编写了一个小灯箱,用于在我的网站上查看图片。为了保持快速加载过程,我想“延迟加载”全尺寸图像。目前浏览器始终加载预览 (test.jpg?size=520px) 和全尺寸图像 (test.jpg)。
是否有任何简单的解决方案来防止浏览器在单击图像之前加载全尺寸图像?
- 该网站仅使用最少的 javascript - 但我没有找到“无 javascript”解决方案。此外,我更喜欢一种不需要在单击鼠标时添加的 .js 文件中的大型 html 字符串的解决方案。
- 大多数延迟加载脚本仅更改图像标记内的属性键。但是,对于 HTML 5,这不再是一种有用的方法。也许可以更改
<picture>
标记 (<picture>
<<>><picture-disabled>
) 并预取全尺寸图像?
HTML:
<div class="imagecc">
<picture onclick="lightboxshow('test004.jpg')">
<source type="image/webp" srcset="test004.webp?size=520px">
<img src="test.jpg?size=520px" alt="...">
</picture>
<p class="imgcaption">...</p>
</div>
<div id="test004.jpg" class="imageccbox" onclick="lightboxclose(this)">
<div class="imageccboxpicture">
<picture>
<source type="image/webp" srcset="test004.webp">
<img src="test.jpg">
</picture>
</div>
</div>
CSS:
.imageccbox {
display: none;
position: fixed;
z-index: 9999;
top: 0; left: 0;
width: 100%;
height: 100%;
background: linear-gradient(180deg, rgba(255,255,255,0.9), rgba(255,255,255,1));
text-align: center;}
.imageccbox:target {
background: rgba(255,255,255,0.8);
display: block;
outline: none;}
.imageccbox:target > .imageccboxpicture {opacity: 1.0;}
.imageccboxpicture {
margin-top: 5%;
opacity: 0.4;
transition: opacity 500ms linear;
cursor: none;}
JavaScript:
function lightboxshow(object) {
var imageccbox = document.getElementById(object);
imageccbox.style.display='block';
setTimeout(function() {imageccbox.getElementsByClassName("imageccboxpicture")[0].style.opacity = 1.0;}, 25);
window.location.hash = object;}
最佳答案
考虑使用 <template>
element .它只是网络组件的一部分。
基本上,您可以在 <template>
中填充任何内容您不希望浏览器加载的内容,然后在您希望加载内容时移动内容。你做出那个改变onload
, 或 onclick
,或您喜欢的任何其他事件。无论哪种方式,都不需要大量的 JavaScript 操作,而且您不需要任何库。
看看这个教程:Quick trick: using template to delay loading of images .
不支持该标签的旧版浏览器将无法获得延迟加载的好处,因此也有不错的渐进式增强功能。
另一个引用:http://webcomponents.org/articles/introduction-to-template-element/
关于javascript - HTML 5 的 <picture> 延迟加载(没有 jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501421/