2013-02-04 166 views
0

直接調用預加載功能沒有任何問題。但是,當預緊()被調用的onClick,甚至圖像的加載後,不能結束其處理,並且可以在瀏覽器中被視爲「載入中...」點擊使用javascript預加載圖片

function preload(images) { 
    if (document.images) { 
     var i = 0; 
     var imageArray = new Array(); 
     imageArray = images.split(','); 
     var imageObj = new Image(); 
     for(i=0; i<=imageArray.length-1; i++) { 
      document.write('<img src="' + imageArray[i] + '" width="335px" height="180px" alt="[Alternative text]" />'); 
      imageObj.src=imageArray[i]; 
     } 
    } 
} 

<a href="javascript:onclick=preload('1.jpg,2.jpg');">Gallery</a> 
+0

你想要什麼到底是什麼?要預加載圖像,以便它們可以立即顯示或將它們寫入頁面以便用戶看到它們? –

回答

1

你無法在這個網頁後調用document.write被加載。如果你想添加一些東西到頁面上,你必須調用DOM操作函數,如document.createElement (see example)

但是你在你的函數中做什麼看起來並不像預加載,而是像在頁面中直接插入圖像。

如果要預加載圖像,即要求瀏覽器將其緩存以便稍後立即可用,則最好使用XmlHttpRequest而不是創建Image元素。發出XmlHttpRequest請求不會使瀏覽器顯示沙漏,用戶也不會覺得有什麼事情發生。

上週我爲此製作了一個小型「庫」,可以輕鬆預壓資源。

var preload = (function(){ 
    var queue = [], nbActives = 0; 
    function bip(){ 
     if (queue.length==0 || nbActives>=4) return; 
     nbActives++; 
     var req = new XMLHttpRequest(), task=queue.shift(); 
     req.open("GET", task.src, true); 
     req.onload = function() { 
      nbActives--; 
      bip(); 
      if (task.callback) task.callback(task.src); 
     }; 
     req.send(); 
    } 
    return function(src, priority, callback) { 
     queue[priority?'unshift':'push']({src:src, callback:callback}); 
     bip(); 
    } 
})(); 

用法:

preload('path/to/file.png'); // preload the file 

preload('path/to/file.png', true); // preload the file with high priority 

preload('path/to/file.png', false, callback); // preload the file and be notified when it's finished 

Github上庫:https://github.com/Canop/preload

+0

對不起,請再次查看這個帖子 – Madhusudhan

+0

我在onClick()時加載圖片,因爲減少加載時間並在需要時顯示圖片。 – Madhusudhan

+0

好的,所以我可能會建議你使用我製作的庫。請參閱編輯。 –