簡體   English   中英

延遲加載圖像后啟動javascript

[英]Start javascript after lazy load images

我的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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM