Create an Image object to realize pre-download of the image. If the image already exists in the browser cache, directly call the callback function. Use the onload event to determine whether the image is loaded.
function loadImage(url, callback) { var img = new Image(); //Create an Image object to implement pre-download of the image img.src = url; if(img.complete) { //If the image already exists in the browser cache, directly call the callback function callback.call(img); return; // Return directly, no longer need to process the onload event} img.onload = function () { //Call call the callback function asynchronously when the image is downloaded. callback.call(img);//Replace this of the callback function with an Image object}; }; </pre><pre code_snippet_id="395795" snippet_file_name="blog_20140617_3_4709132" name="code"><pre name="code"><!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 whether the image is loading complete</title> </head> <body> <img id="img2" src="images/1.jpg" /> </body> </html> <script language="JavaScript"> document.getElementById("img2").onload = function () { alert("Image loading completed"); } </script>