Home  >  Article  >  Web Front-end  >  js determines whether the image is loaded and implements pre-downloading of the image_javascript skills

js determines whether the image is loaded and implements pre-downloading of the image_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:39:282021browse

Create an Image object to pre-download the image. If the image already exists in the browser cache, call the callback function directly and use the onload event to determine whether the image is loaded

function loadImage(url, callback) { 
var img = new Image(); //创建一个Image对象,实现图片的预下载 
img.src = url; 

if(img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数 
callback.call(img); 
return; // 直接返回,不用再处理onload事件 
} 
img.onload = function () { //图片下载完毕时异步调用callback函数。 
callback.call(img);//将回调函数的this替换为Image对象 
}; 
};
 
<pre name="code" class="html"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<title>判断图片是否加载完成</title> 

</head> 
<body> 
<img id="img2" src="images/1.jpg" /> 
</body> 
</html> 
<script language="JavaScript"> 
document.getElementById("img2").onload = function () { 
alert("图片加载已完成"); 
} 
</script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn