99久久99久久精品免观看,国产精品久久久久国产精品,国产黄色录像视频,免费的黄色毛片,国产一区精品普通话对白,色妞妞成人在线观看,最新aⅴ福利在线观看免费

綠色資源網(wǎng):您身邊最放心的安全下載站! 最新軟件|熱門排行|軟件分類|軟件專題|論壇轉(zhuǎn)帖|廠商大全

綠色資源網(wǎng)

技術(shù)教程
您的位置:首頁網(wǎng)頁設(shè)計網(wǎng)頁特效 → javascript圖片預(yù)加載技術(shù)

javascript圖片預(yù)加載技術(shù)

我要評論 2011/03/15 09:55:50 來源:綠色資源網(wǎng) 編輯:綠色資源站 [ ] 評論:0 點(diǎn)擊:229次

由于javascript無法獲取img文件頭數(shù)據(jù),必須等待其加載完畢后才能獲取真實的大小,所以lightbox類效果為了讓圖片居中顯示,導(dǎo)致其速度體驗要比直接輸出的差很多。而本文所提到的預(yù)加載技術(shù)主要是讓javascript快速獲取圖片頭部數(shù)據(jù)的尺寸。

一段典型的使用預(yù)加載獲取圖片大小的例子:

var imgLoad = function (url, callback) {
var img = new Image();

img.src = url;
if (img.complete) {
callback(img.width, img.height);
} else {
img.onload = function () {
callback(img.width, img.height);
img.onload = null;
};
};

};

可以看到使用onload的方式必須等待圖片加載完畢,其速度不敢恭維。

web應(yīng)用程序區(qū)別于桌面應(yīng)用程序,響應(yīng)速度才是最好的用戶體驗。如果想要速度與優(yōu)雅兼得,那就必須提前獲得圖片尺寸,如何在圖片沒有加載完畢就能獲取圖片尺寸?

十多年的上網(wǎng)經(jīng)驗告訴我:瀏覽器在加載圖片的時候你會看到圖片會先占用一塊地然后才慢慢加載完畢,并且這里大部分的圖片都是沒有預(yù)設(shè)width與height屬性的,因為瀏覽器能夠獲取圖片的頭部數(shù)據(jù)?;诖耍恍枰褂胘avascript定時偵測圖片的尺寸狀態(tài)便可得知圖片尺寸就緒的狀態(tài)。

實現(xiàn)代碼:

var imgReady = function (url, callback, error) {
var width, height, intervalId, check, div,
img = new Image(),
body = document.body;

img.src = url;

// 從緩存中讀取
if (img.complete) {
return callback(img.width, img.height);
};

// 通過占位提前獲取圖片頭部數(shù)據(jù)
if (body) {
div = document.createElement('div');
div.style.cssText = 'visibility:hidden;position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden';
div.appendChild(img)
body.appendChild(div);
width = img.offsetWidth;
height = img.offsetHeight;

check = function () {
if (img.offsetWidth !== width || img.offsetHeight !== height) {
clearInterval(intervalId);
callback(img.offsetWidth, img.clientHeight);
img.onload = null;
div.innerHTML = '';
div.parentNode.removeChild(div);
};
};

intervalId = setInterval(check, 150);
};

// 加載完畢后方式獲取
img.onload = function () {
callback(img.width, img.height);
img.onload = img.onerror = null;
clearInterval(intervalId);
body && img.parentNode.removeChild(img);
};

// 圖片加載錯誤
img.onerror = function () {
error && error();
clearInterval(intervalId);
body && img.parentNode.removeChild(img);
};

};

是不是很簡單?這樣的方式獲取攝影級別照片尺寸的速度往往是onload方式的幾十多倍,而對于web普通(800×600內(nèi))瀏覽級別的圖片能達(dá)到秒殺效果。

關(guān)鍵詞:javascript

閱讀本文后您有什么感想? 已有 人給出評價!

  • 0 歡迎喜歡
  • 0 白癡
  • 0 拜托
  • 0 哇
  • 0 加油
  • 0 鄙視