Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 16:39:28
Original
1988 people have browsed it

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对象 
}; 
};
Copy after login
 
<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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!