new Image()的用途

new Image()用途总结:

 

1、图片预加载

     在做游戏时,为了使图片能快打开可以做预加载。
     原理:创建image对象,将image对象的src分别指向需加载的图片地址,图片被请求,因为Image对象没有显示在页面上,所以不会对页面布局产生影响。   

var arr=['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];

var img=new Image();

var n=0
img.src=arr[n];
img.onload=function(){
  n++;
  if(n<arr.length){
    img.src=arr[n];
  }
}

 
2、向服务器发送统计请求
 
     为了做点击量或访问量统计时,向服务器发送请求。
     原理:创建image对象,image对象的src为请求服务器的地址,当image对象请求图片资源时,服务发送成功。为了避免浏览器缓存导致的不发送请求,可在请求地址后加时间戳。
obj.onclick=function(){
          (new Image()).src="服务器地址"+"?_t="+new Date().getTime();
     }
 
3、创建image对象
 
      如果需要显示图片,一般会提前把结构写好吧。
var img = new Image();  img.src="1.jpg";
  document.getElementsByTagName('body')[0].appendChild(img);

 

 
  
 
 
posted @ 2014-10-17 17:22  -nothing-  阅读(8557)  评论(0编辑  收藏  举报