图片预加载与懒加载
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>img ready</title> </head> <body> <div> <p> <button id="testReadyBtn">开始加载图片</button> <button id="clsCacheBtn">清空缓存</button> <p>(如果图片加载过后,浏览器会缓存)</p> </p> <div id="status" style="display:none"> <p><strong>imgReady:</strong><p> <p id="statusReady"></p> <p><strong>imgLoad:</strong></p> <p id="statusLoad"><p> </div> <div id="imgWrap"></div> <div style="display:none"></div> </div> </body> <script> 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); }; // 通过占位提前获取图片头部数据 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); }; }; </script> <script> /* demo script */ window.onload = function () { var imgUrl = 'http://www.planeart.cn/demo/imgReady/vistas24.jpg?', testReadyBtn = document.getElementById('testReadyBtn'), clsCacheBtn = document.getElementById('clsCacheBtn'), status = document.getElementById('status'), statusReady = document.getElementById('statusReady'), statusLoad = document.getElementById('statusLoad'), imgWrap = document.getElementById('imgWrap'); 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; }; }; }; testReadyBtn.onclick = function () { var that = this; that.disabled = true; status.style.display = 'block'; statusLoad.innerHTML = statusReady.innerHTML = 'Loading...'; imgWrap.innerHTML = '<img src="' + imgUrl + '" />'; // 使用占位方式快速获取大小 imgReady(imgUrl, function (width, height) { statusReady.innerHTML = 'width:' + width + '; height:' + height; }, function () { statusReady.innerHTML = 'Img Error!'; }); // 使用传统方式获取大小 imgLoad(imgUrl, function (width, height) { statusLoad.innerHTML = 'width:' + width + '; height:' + height; that.disabled = false; }, function () { statusLoad.innerHTML = 'Img Error!'; that.disabled = false; }); }; clsCacheBtn.onclick = function () { imgUrl += new Date().getTime(); status.style.display = 'none'; imgWrap.innerHTML = ''; }; }; </script> </html>
2、懒加载实现:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>原生Js图片延迟加载</title> <style type="text/css"> *{margin: 0;padding: 0} img.scrollLoading{border: 1px solid #ccc;display:block;margin-top: 10px;} </style> </head> <body> <div id="content"> </div> </body> </html> <script type="text/javascript"> var _CalF = { zsl: function(object) { //选择器 if (object === undefined) return; var getArr = function(name, tagName, attr) { var tagName = tagName || '*', eles = document.getElementsByTagName(tagName), clas = (typeof document.body.style.maxHeight === "undefined") ? "className": "class"; //ie6 attr = attr || clas, Arr = []; for (var i = 0; i < eles.length; i++) { if (eles[i].getAttribute(attr) == name) { Arr.push(eles[i]); } } return Arr; }; if (object.indexOf('#') === 0) { //#id return document.getElementById(object.substring(1)); } else if (object.indexOf('.') === 0) { //.class return getArr(object.substring(1)); } else if (object.match(/=/g)) { //attr=name return getArr(object.substring(object.search(/=/g) + 1), null, object.substring(0, object.search(/=/g))); } else if (object.match(/./g)) { //tagName.className return getArr(object.split('.')[1], object.split('.')[0]); } }, getPosition: function(obj) { //获取元素在页面里的位置和宽高 var top = 0, left = 0, width = obj.offsetWidth, height = obj.offsetHeight; while (obj.offsetParent) { top += obj.offsetTop; left += obj.offsetLeft; obj = obj.offsetParent; } return { "top": top, "left": left, "width": width, "height": height }; } }; //添加图片list var _temp = []; for (var i = 1; i < 21; i++) { _temp.push('<img class="scrollLoading" data-src="http://images.cnblogs.com/cnblogs_com/Darren_code/311197/o_' + i + '.jpg" src="//images0.cnblogs.com/blog/150659/201306/23160223-c81dd9aa9a2a4071a47b0ced2c9118bc.gif" /><br />图片' + i); } _CalF.zsl("#content").innerHTML = _temp.join(""); function scrollLoad() { this.init.apply(this, arguments); } scrollLoad.prototype = { init: function(className) { var className = "img." + className, imgs = _CalF.zsl(className), that = this; this.imgs = imgs; that.loadImg(); window.onscroll = function() { that.time = setTimeout(function() { that.loadImg(); }, 400); } }, loadImg: function() { var imgs = this.imgs.reverse(), //获取数组翻转 len = imgs.length; if (imgs.length === 0) { clearTimeout(this.time); return; } for (var j = len - 1; j >= 0; j--) { //递减 var img = imgs[j], imgTop = _CalF.getPosition(img).top, imgSrc = img.getAttribute("data-src"), offsetPage = window.pageYOffset ? window.pageYOffset: window.document.documentElement.scrollTop, //滚动条的top值 bodyHeight = document.documentElement.clientHeight; //body的高度 if ((offsetPage + bodyHeight / 2) > (imgTop - bodyHeight / 2)) { img.src = imgSrc; this.imgs.splice(j, 1); } } } } var img1 = new scrollLoad("scrollLoading"); </script> 获取屏幕的分辨率 <script type="text/javascript"> document.write('您的显示器分辨率为:\n' + screen.width + '*' + screen.height + '</br>'); var ww = document.getElementById("con").offsetWidth, w = screen.width/ww, h = screen.height/ww, r = Math.round(Math.sqrt(w*w + h*h) / 2.54); document.write('您的显示器尺寸为:\n' + (screen.width/ww).toFixed(1) + '*' + (screen.height/ww).toFixed(1) + ' cm, '+ r +'寸<br/>'); </script>