---
title: "js 图片延迟加载 lazy_ load 0.2"
author: "yunmoxue"
date: "2012-03-28T17:11:48Z"
tags: []
categories: ["Web前端"]
slug: "js-lazy-load-0-2"
draft: false
lastmod: "2013-02-18T12:09:05Z"
id: 1467223
url: "https://ymx.iteye.com/blog/1467223"
---

```javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>lazy_load 0.2  图片延迟加载</title>
<style>
	.lazyimg{
		width:150px;
		height:150px;
		background:url('imgs/loading.gif') 50% 50% no-repeat transparent;
		border: solid 1px #efeffe;
	}
</style>
</head>

<body>
	<script type="text/javascript">  
        window.onload = function(){
			//load_img();
			//为了显示loading样式,延迟2秒加载图片,实际开发中直接调用就行.
			setTimeout(function(){load_img();},2000);
			
			function load_img(){
				var imgs = document.getElementsByTagName('img');
				var imgs_length = imgs.length;
				for(var i=0;i<imgs_length;i++){
					var old_img = imgs[i];
					if(!old_img.getAttribute('lazysrc'))
						continue;
					var img = document.createElement('img');
					img.onload = (function(old_img,img){ 
						return function(){
							old_img.src = img.src; 
						}
					})(old_img,img);
					img.src = old_img.getAttribute('lazysrc');  
				}
			}
        }
    </script>  
    <img src="imgs/blank.gif" lazysrc="imgs/1.jpg" class="lazyimg" /> 
    <img src="imgs/blank.gif" lazysrc="imgs/2.jpg" class="lazyimg" /> 
    <img src="imgs/blank.gif" lazysrc="imgs/3.jpg" class="lazyimg" /> 
    <img src="imgs/blank.gif" />
    <img src="imgs/blank.gif" lazysrc="" />

</body>
</html>

```