1. 学习图片预加载,最简单的那种,就是点击一个按钮进行预加载,然后再显示到页面中,主要注意以下几点:
(1)注意使用document.createElement('img')和使用new Image()两种方法创建img元素的不同。前者是创建了一个节点,可以通过document.body.appendChild()添加到dom中,后者只是一个Image对象,不能通过appendChild添加到DOM中。
(2)只要设置了img的src属性,浏览器就开始下载图片。
(3)通过img.complete属性可以判断该图片是否存在于缓存中,如果存在于缓存中,那该属性为true,如果不存在与缓存中,为false
代码如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="../js/JSEvent.js"></script>
<script type="text/javascript">
function callback(){
alert("loaded finish!"+this.width+" | "+this.height);
var pic=document.getElementById("pic");
this.width>=380?pic.width=380:this.width;
this.height>=460?pic.height=460:this.height;
pic.src=this.src;
}
function loadImage(){
var url=document.getElementById("path").value;
load(url,callback);
}
function load(url,callback){
var img=new Image();
img.src=url;
if(img.complete){
alert("it is in cache");
callback.call(img);
}else{
img.οnlοad=function(){
img.οnlοad=null;//加载成功之后,就移除onload事件
alert("it isn`t in cache");
callback.call(img);
};
}
}
</script>
<style type="text/css">
#displayPicDiv{
width: 400px;
height: 500px;
position: absolute;
top:50%;
left: 50%;
margin-top: -250px;
margin-left: -200px;
background-color: green;
}
#picDiv{
position: absolute;
left: 50%;
top: 50%;
width: 380px;
height: 460px;
margin-top: -230px;
margin-left: -190px;
background-color: yellow;
}
</style>
</head>
<body>
<div style="margin:20px 20px">
<input type="text" id="path"/><br>
<input type="button" οnclick="loadImage()"/><br>
</div>
<div id='displayPicDiv'>
<div id="picDiv">
<img id='pic'/>
</div>
</div>
</body>
</html>