new Image()的用途

new Image()用途总结:浏览器

 

一、图片预加载缓存

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

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

var img=new Image();app

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

 
二、向服务器发送统计请求
 
     为了作点击量或访问量统计时,向服务器发送请求。
     原理:建立image对象,image对象的src为请求服务器的地址,当image对象请求图片资源时,服务发送成功。为了不浏览器缓存致使的不发送请求,可在请求地址后加时间戳。
obj.onclick=function(){
          (new Image()).src="服务器地址"+"?_t="+new Date().getTime();
     }
 
三、建立image对象
 
      若是须要显示图片,通常会提早把结构写好吧。
var img = new Image();  img.src="1.jpg";
  document.getElementsByTagName('body')[0].appendChild(img);
 
相关文章
相关标签/搜索