延迟加载图像后启动javascript



我在javascript上遇到了问题。该脚本导致我网站上的三个元素大小相同。我想通过延迟加载来加载我的照片。这会使渲染不正确,因为元素的大小是由没有图像的脚本计算的。是否可以给 javascript 一个函数,只有在延迟加载成功加载图像后才会启动?

<script type="text/javascript">
jQuery(document).ready(function($){
function kb_equal_height() {
var highest_element = 0;
// Delete the height
$('.navigation-left,.site-content,.widget-area').each(function() {
$(this).removeAttr('style');
});
// Check which element is highest
$('.navigation-left,.site-content,.widget-area').each(function() {
if ($(this).height() > highest_element) {
highest_element = $(this).height();
}
});
// Assign this height to all elements
$('.navigation-left,.site-content,.widget-area').each(function() {
$(this).height(highest_element);
});
};
window.onload = kb_equal_height;
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(kb_equal_height, 100);
});
});
</script>

您可以使用image.onload在图像完成加载时调用函数

您可能不会在这里真正看到它的实际效果,因为图像可能不会花费足够长的时间来加载您看到中间状态,但它可以工作

如果您想再次查看缓存,则需要清理缓存,因为您的浏览器将在第二次、第三次从缓存中加载图像......次

let nbCat = 0
let div = document.getElementById("nbImg")
Array.from(document.getElementsByClassName("doAction")).forEach(img => {
img.onload = imgLoaded // your function here
})
function imgLoaded(e) {
nbCat++
div.textContent = nbCat + " cat" + (nbCat > 1? "s":"") + " loaded"
}
img {
max-height: 50vh
}
<img class="doAction" src="https://r.hswstatic.com/w_907/gif/tesla-cat.jpg">
<img class="doAction" src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg">
<img class="doAction" src="https://pre00.deviantart.net/5d96/th/pre/f/2012/103/d/d/dd0d35acf8ea1817dffe7677f018b5a4-d4vzsbg.jpg">
<img class="doAction" src="https://pre00.deviantart.net/758d/th/pre/f/2018/006/2/7/tigerfieldadjusted_by_mssylviarose-dbz65qt.jpg">
<div id="nbImg">no cat loaded</div>

最新更新