DIV CSS 佈局教程網

用 JavaScript 實現圖片的順序(序列化)載入
編輯:關於JavaScript     

當頁面需要載入大量圖片時,若一次性全部向伺服器請求,容易造成頻寬擁擠與延遲。本文示範一種「一張載完再載下一張」的順序載入方式,能有效分散請求、降低伺服器壓力,特別適合類似 Google 地圖那樣由無數小圖拼成的應用。

 function Load_pic(arr){ this.loop_f=function(i,o_file,len,f,obj){ if(i<len-1){ i=i+1; f(i,o_file,len,obj); } }; this.creat_pic=function(i,o_file,len,obj){ var f=arguments.callee, doc=document, image = doc.createElement("img"); image.src =o_file[i]; i<len?doc.getElementsByTagName("body")[0].appendChild(image):''; if(navigator.userAgent.indexOf("MSIE")>0){ if($.browser.version==6.0 || $.browser.version==9.0){ //IE9和IE6一樣 微軟真是怪異 image.onreadystatechange = function () { if (image.readyState == "complete"){ obj.loop_f(i,o_file,len,f,obj); } }; }else{ ie7imagetime = window.setInterval(function(){ var rs = image.readyState; if(rs=="complete"){ window.clearInterval(ie7imagetime); obj.loop_f(i,o_file,len,f,obj); }else{ return; } },200); } }else{ image.onload = function () { if (image.complete == true){ obj.loop_f(i,o_file,len,f,obj); } }; } }; if(arr.constructor===Array){ var len=arr.length, i=0; i<len?this.creat_pic(i,arr,len,this):''; }; } //調用方法 new Load_pic([ 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/0_0.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/0_1.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/0_2.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/0_3.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/1_0.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/1_1.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/1_2.gif', 'https://gomap.dashilan.cn/jquery-mobile/map/cq/1/img_1/1_3.gif' ]); //注意要調用jquery 用於判斷浏覽器 

這段程式碼的重點在於「監聽單張圖片載入完成後,才觸發下一張」的遞迴機制:creat_pic 建立 img 並指定 src,等它載入完成(透過 onload 或舊版 IE 的 onreadystatechange)後,再由 loop_f 遞迴處理下一張。其中還針對 IE6/IE9 與其他 IE 版本分別用不同方式偵測 readyState,展現了照顧舊瀏覽器的細節。這種序列化載入策略能有效避免一次發出大量請求,讓大型圖集或地圖應用載入得更平順。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved