JS to determine whether the picture is loaded and realize the pre-download of the picture

Source: Internet
Author: User

Create an Image object to achieve the image of the pre-download, if the picture already exists in the browser cache, call the callback function directly, use the OnLoad event to determine whether the picture is loaded complete

01 function LoadImage (URL, callback) {
02 var img = new Image (); Create an Image object to achieve a pre-download of the picture
03 img.src = URL;
04
05 if (img.complete) {//If the picture already exists in the browser cache, call the callback function directly
06 Callback.call (IMG);
07 Return Return directly without handling the OnLoad event
08 }
09 Img.onload = function () {////callback functions are called asynchronously when the picture is downloaded.
10 Callback.call (IMG);//Replace the callback function with this with an Image object
11 };
12 };
01 </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" >
02
03
04 <meta http-equiv= "Content-type" content= "text/html; Charset=iso-8859-1 ">
05 <title> Determine whether the picture is loaded </title>
06
07
08 <body>
09
10 </body>
11
12 <script language= "JavaScript" >
13 document.getElementById ("Img2"). onload = function () {
14 Alert ("Picture loading completed");
15 }
16 </script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.