6

js图片延时加载(jquery特效)

 3 years ago
source link: https://blogread.cn/it/article/5645?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

js图片延时加载(jquery特效)

浏览:2858次  出处信息

    前段时间朋友说让给做一个js延时加载图片人功能,原来也的网上见过这些,但是没有具体的研究。今天学习了下,发出来和大家一直分享。至于延时加载的好处我在这里就不说了,好多朋友都说可以减少服务器短时间的请求数量。

    一、原理分析

     1.可显示区域的的图片正常显示,不可显示的不去请求,

    2.当滚动滚动条时,计算可显示的图片,把图片的src的真实路径写入。

    这里我用的是jquery来做的,当然大家如果明白了原理,用什么做都可以做出很不错的效果。

    下面看代码

<!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=gb2312" />

<script src="http://blog.suiyidian.cn/texiao/jquery-1.3.1.js" type="text/javascript"></script>
<title>js图片延时加载特效</title>

<script type="text/javascript">

$(function(){


 var d = new Array();
for (i = 0; i < $("img").length; i++) {

 d[i] = $("img").eq(i).attr("name");

for (i = 0; i < $("img").length; i++) {

 if ($("img").eq(i).offset().top > document.documentElement.clientHeight + $(window).scrollTop()) {

  $("img").eq(i).attr("src", "hc.gif");

 } else {

  $("img").eq(i).attr("src", d[i]);
 }

$(window).scroll(function() {

 for (i = 0; i < $("img").length; i++) {

  if ($("img").eq(i).offset().top > document.documentElement.clientHeight + $(window).scrollTop()) {

   $("img").eq(i).attr("src", "hc.gif");

  } else {

   $("img").eq(i).attr("src", d[i]);
  }

})


 })
</script>
</head>
<body>
<img name="http://hj.bbs.nen.com.cn/attachments/10063010304e0ab3ca1c10b81c.jpg" src="hc.gif"  />
<br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>

    这上面是代码,大家可以细细的研究一下,

    DEMO效果

觉得文章有用?立即:

和朋友一起 共学习 共进步!

建议继续学习:

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK