jquery实现 图片延迟加载

图片延迟加载的大致的原理是,对于图片标签不是把图片的路径指定到src属性上,src属性指定一个非常小的空白图片,真正的图片地址设置到一个自定义的属性上,比如file,这样img标签就是这样:<img src="blank.jpg" file="00xx.jpg"/>或者背景直接把一张小的空白图作为背景色。

我的设计思想采用第二种:

1:先把刷新的小图片 作为图片的背景图片,根据onload判断图片是否加载完成onload官方手册的说明:

如果绑定给window对象,则会在所有内容加载后触发,包括窗口,框架,对象和图像。如果绑定在元素上,则当元素的内容加载完毕后触发。

注意:只有当在这个元素完全加载完之前绑定load的处理函数,才会在他加载完后触发。如果之后再绑定就永远不会触发了。所以不要在$(document).ready()里绑定load事件,因为jQuery会在所有DOM加载完成后再绑定load事件。

2:error可以判断是否图片失效或者url失效:error官方手册说明

对于error事件,没有一个公众的标准。在大多数浏览器中,当页面的JavaScript发生错误时,window对象会触发error事件;当图像的src属性无效时,比如文件不存在或者图像数据错误时,也会触发图像对象的error事件。 备注ie下失效,所以可以在最后一部全部清除背景图片


3:最后在执行清除背景图片等等善后工作


<!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>jQuery加载图片</title>

    <style type="text/css">

        h1{color:Green;}

        body{ background-color:#EEEEEE ; }

        #load{border:solid 1px blue; width:500px; height:333px; overflow:hidden;}

        .loading{background: url(http://www.jquery001.com/images/gif/al_loading.gif) no-repeat center center;}

    </style>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function() {
            var img = new Image();
				
            //图片加载加载后执行
            $("img").load(function() {
				
                //图片默认隐藏
				
                $(this).hide();

                //移除小动画
				
		$(".loading").removeClass("loading").append(this);

               		 //使用fadeIn特效

               	 $(this).fadeIn("5000");

            })
			
			//加载失败时的处理
            $("img").error(function() {
			<!--$("img").replaceWith("没有图片");-->
			$(this).attr("src", "http://www.blogkid.cn/wp-content/uploads/2008/04/memcached_shell_2.JPG");
	

            })

            //最后设置src

           <!-- .attr("src", "http://www.jquery001.com/images/demo/2010/anyixuan.jpg");-->
				<!--$(".loading").removeClass("loading")-->
        });

    </script>

</head>

<body>

    <h1>jQuery加载图片</h1>

    <div id="load" class="loading"> <img src="http://www.moredoo.com/Mobile/share/124650442011year6month7day23hour57min14sec.jpg" style=" height:auto" id='uu1'>
    <br />
    </div>
    
<img src="http://www.jquery001.com/images/demo/2010/anyixuan.jpg" style="  float:right" id='uu1'>
</body>

</html>
常用的几张加载延时进度条 可以作为收藏起来 哈哈




posted @ 2011-07-29 14:11  y0umer  阅读(300)  评论(0编辑  收藏  举报