簡體   English   中英

這是在Javascript / Jquery(帶有動畫)中預加載圖像的正確方法嗎?

[英]Is this a correct way to preload an image in Javascript / Jquery (with animation)?

我正在嘗試在HTML圖片加載時顯示基本動畫。

這是正確的方法嗎?

      //display the (small image) animation
      var preloader = new Image();
      preloader.src = 'img/preload.gif';
      $('#myDiv').append(preloader);

      //load big image and hide peload animation when finished
      var img = new Image();
      img.onload = function () { $(preloader).hide(); preloader = null; } ;
      img.src = 'img/bigImage.jpg';
      $('#myDiv').append(img);

我不確定這是否正確:盡管小動畫可以在我的瀏覽器中使用,但始終會加載小動畫,即使大圖像已經加載並且位於緩存中也是如此。 有沒有一種方法可以停用此功能,或者可以考慮使用另一種方法來處理帶有小動畫的圖像預加載?

謝謝

這是我的處理方式:

var preloader = new Image(),
    img       = new Image(),
    div       = document.getElementById('myDiv');

img.onload = function () {
    preloader = null; 
    div.innerHTML = '';
    div.appendChild(this);
};

img.src = 'img/bigImage.jpg';

// if it's not in cache or not loaded (has no size), show the preloader
if (! (img.complete || img.width+img.height > 0) ) {
    preloader.src = 'img/preload.gif';
    div.innerHTML = '';
    div.appendChild(preloader);
}

暫無
暫無

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

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