2012-09-08 197 views
0

我目前正在使用單選按鈕和複選框來顯示基於值的圖像。我注意到圖像在開始時緩慢加載。例如,已經用「display:none」(其src屬性已經設置)預先創建了圖像元素,所以我唯一要做的就是使用display屬性。有沒有預加載圖像? EXAMPLE頁面啓動期間加載圖像

JS

<script> 
function check_value(currentElement, val, id, type) { 
    var el = document.getElementById("imgBox" + id); 
    if (val > 0 && val < 4) { //will trigger when [1,2,3] 

     if(currentElement.checked) 
     { 
      el.src = "images/" + type + val + ".jpg"; 
      el.style.display = ""; 
     } 
     else 
     { 
      el.src = ""; 
      el.style.display = "none"; 
     }  

    } 
}  
</script> 

HTML

<h2>Choose a bike</h2> 
<form name="builder"> 
    <input type="radio" name="field" onclick='check_value(this, 1, 1, "bike")'/> KAWASAKI KX 450F<br /> 
    <input type="radio" name="field" onclick='check_value(this, 2, 1, "bike")'/> 2010 Yamaha Road Star S<br /> 
    <input type="radio" name="field" onclick='check_value(this, 3, 1, "bike")'/> Aprilia RSV4<br /> 
</form> 

回答

1

是的!預載圖片是很容易的,如果你有JQuery的:

$.fn.preload = function() { 
    this.each(function(){ 
     $('<img/>')[0].src = this; 
    }); 
} 

$(['some-image.gif']).preload(); 

還要檢查這個資源:http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

+0

顯然,它被認爲是不好的S.O形式發佈基於jQuery的答案標記'JavaScript'問題。另外,不是Img標籤'$('img')'的選擇器? – 5arx

0

下面是我爲自己前一段時間做了一個功能:http://pastebin.com/GeBawE8r

你可以用它如下:

var loader = new imagePreloader(); 

// Object containing the names of the imgs as keys and url as values 
loader.list = {name: "url"...}; 

// function to call when done loading everything 
loader.onload = ... 

// function to call at each time it loades a single image of the list 
loader.each = ... 

// function to call when unable to load one of the images 
loader.onerror = ... 

// set this to true to continue even if some of the images fail to load 
loader.ignoreErrors = true/false 

// Starts loading the images 
loader.load(); 

它完成加載屬性後ready將被設置爲true,您可以訪問ŧ他在list對象中顯示圖像。

if(loader.ready) 
    alert(loader.list.myImageName); // Image object 

http://jsfiddle.net/uttZw/1