Js determines whether the image is loaded and realizes the image's pre download

  • 2020-03-30 03:43:24
  • OfStack

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


function loadImage(url, callback) { 
var img = new Image(); //Create an Image object to pre-download the Image
img.src = url; 

if(img.complete) { //If the image already exists in the browser cache, call the callback function directly
callback.call(img); 
return; //Return directly, without having to deal with the onload event
} 
img.onload = function () { //The callback function is called asynchronously when the image is downloaded.
callback.call(img);//Replaces this of the callback function with an Image object
}; 
};

 </pre><pre code_snippet_id="395795" snippet_file_name="blog_20140617_3_4709132" name="code" class="html"><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> Determine if the image is loaded </title> 

</head> 
<body> 
<img id="img2" src="images/1.jpg" /> 
</body> 
</html> 
<script language="JavaScript"> 
document.getElementById("img2").onload = function () { 
alert(" Image loading is complete "); 
} 
</script>

Related articles: