html+js實現圖片預先載入(非同步載入)

來源:互聯網
上載者:User

標籤:http   io   ar   使用   java   sp   資料   on   2014   

在前端設計時,為了讓某縣頁面的圖片即使緩衝到瀏覽器中,一般使用預先載入技術,但更為確切的應該稱為非同步載入,因為對線程不會造成阻塞。

核心代碼

<script type="text/javascript">  function loadImage(id,src,callback)  {var img = new window.Image();//當圖片成功載入到瀏覽器緩衝img.onload =function(evt)  {if(typeof(img.readyState)==‘undefined‘){    img.readyState = ‘undefined‘;}//在IE8以及以下版本中需要判斷readyState而不是completeif ((img.readyState==‘complete‘||img.readyState=="loaded")||img.complete==true) {    callback({‘msg‘:‘ok‘,‘src‘:src,‘id‘:id});}else{   img.onreadystatechange(e);}};img.onerror = function(evt) {    callback({‘msg‘:‘error‘,‘id‘:id}); }                       img.onreadystatechange = function(e){     //次方法只有IE8以及一下版本會調用}    img.src=src;}</script>

深情的測試一下吧。

<!doctype html><html><head><meta charset="utf-8" /><title>非同步(預先載入)載入圖片</title><meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1.0" /></head><body> <img src="loading.gif" id="display_images"><script type="text/javascript">  function loadImage(id,src,callback)  {var img = new window.Image();//當圖片成功載入到瀏覽器緩衝img.onload =function(evt)  {if(typeof(img.readyState)==‘undefined‘){img.readyState = ‘undefined‘;}//在IE8以及以下版本中需要判斷readyState而不是completeif ((img.readyState==‘complete‘||img.readyState=="loaded")||img.complete==true) {     callback({‘msg‘:‘ok‘,‘src‘:src,‘id‘:id});}else{    img.onreadystatechange(e);}};img.onerror = function(evt) {callback({‘msg‘:‘error‘,‘id‘:id}); }                       img.onreadystatechange = function(e){   //次方法只有IE8以及一下版本會調用} img.src=src;}var loadResult = function(data){data =   data ||{} ;if(typeof(data.msg)!=‘undefined‘){if(data.msg==‘ok‘){        //這裡使用了id擷取元素,有點死板,建議使用這自行改造吧        document.getElementById(‘‘+data.id).src=data.src;//這裡從緩衝讀取資料}else{//這裡圖片載入失敗,我們可以顯示其他圖片,防止大紅叉document.getElementById(‘‘+data.id).src=‘unload.png‘;}}}var s = ‘http://web.2008php.com/2014_Website_appreciate/2014-10-31/20141031133134.jpg‘;loadImage(‘display_images‘,s,loadResult);</script></body></html>

注意:這種用法過於簡單,沒有發揮出效能,請讀者自行改造後,預先載入20張1024*780圖片,然後自動播放。如果是預先載入的,播放時看不見卡頓或顯示不完全的現象。


try doing it.



html+js實現圖片預先載入(非同步載入)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.