Complete determines whether the image is loaded
Thanks to Google, we have found a good method. The simple usage is:
The code is as follows: |
Copy code |
Qim = new Image (); // create an Image; Qim. src = $ preload; // The Image address is the address you want to load; If (qim. complete) {$ ("# cxNfloor" ).html ($ filetoload); // qim. complete indicates whether the image has been loaded. } |
Later I found another method.
The code is as follows: |
Copy code |
$ (""). Load (function (){...}); |
The selector is the image id or class, and the method in the function is the callback function, which is executed after the image is loaded. However, I have tried a lot and the root cause is not that, the correct solution is:
The code is as follows: |
Copy code |
// Jquery method $ ("# ImageId"). load (function (){ Alert ("loading complete! "); }); |
Some friends say that using js is the best, and the method is as follows:
The code is as follows: |
Copy code |
Document. getElementById ("img2"). onload = function (){} |
Find a piece of code online
Example
The code is as follows: |
Copy code |
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, call the callback function directly. Callback. call (img ); Return; // return directly without handling the onload event } Img. onload = function () {// call the callback function asynchronously when the image is downloaded. Callback. call (img); // replace this of the callback function with the Image object. }; }; |
The following describes how to load multiple images.
The code is as follows: |
Copy code |
Var imgdefereds = []; $ ('IMG '). each (function (){ Var dfd = $. Deferred (); $ (This). bind ('load', function (){ Dfd. resolve (); }). Bind ('error', function (){ // Image loading error. Add error handling // Dfd. resolve (); }) If (this. complete) setTimeout (function (){ Dfd. resolve (); },1000 ); Imgdefereds. push (dfd ); }) $. When. apply (null, imgdefereds). done (function (){ Callback (); }); |
This method can avoid window. onload deficiency, but the code is slightly more complicated than window. onload in terms of performance.