BKJIA recommended topics: Answers to questions about JavaScript learning notes
A typical example of getting the image size through pre-loading:
- var imgLoad = function (url, callback) {
- var img = new Image();
-
- img.src = url;
- if (img.complete) {
- callback(img.width, img.height);
- } else {
- img.onload = function () {
- callback(img.width, img.height);
- img.onload = null;
- };
- };
-
- };
We can see that the onload method must wait until the image is loaded, and the speed is not flattering.
Different from desktop applications, web applications provide the best response speed. If you want to achieve both speed and elegance, you must obtain the image size in advance. How can you obtain the image size before loading the image?
More than a decade of online experience tells me that when loading images in a browser, you will see that the images will take up a lot of space before loading them, in addition, most of the images here do not have the default width and height attributes, because the browser can obtain the image header data. Based on this, you only need to use javascript to regularly detect the size status of the image to know that the image size is ready.
Implementation Code:
- Var imgReady = function (url, callback, error ){
- Var width, height, intervalId, check, div,
- Img = new Image (),
- Body = document. body;
-
- Img. src = url;
-
- // Read from the cache
- If (img. complete ){
- Return callback (img. width, img. height );
- };
-
- // Obtain the image header data by placeholder in advance
- If (body ){
- Div = document. createElement ('div ');
- Div.style.css Text = 'visibility: hidden; position: absolute; left: 0; top: 0; width: 1px; height: 1px; overflow: Den den ';
- Div. appendChild (img)
- Body. appendChild (div );
- Width = img. offsetWidth;
- Height = img. offsetHeight;
-
- Check = function (){
- If (img. offsetWidth! = Width | img. offsetHeight! = Height ){
- ClearInterval (intervalId );
- Callback (img. offsetWidth, img. clientHeight );
- Img. onload = null;
- Div. innerHTML = '';
- Div. parentNode. removeChild (div );
- };
- };
-
- IntervalId = setInterval (check, 150 );
- };
-
- // Obtain it after loading
- Img. onload = function (){
- Callback (img. width, img. height );
- Img. onload = img. onerror = null;
- ClearInterval (intervalId );
- Body & img. parentNode. removeChild (img );
- };
-
- // Image loading error
- Img. onerror = function (){
- Error & error ();
- ClearInterval (intervalId );
- Body & img. parentNode. removeChild (img );
- };
-
- };
Is it easy? In this way, the speed of obtaining photography-level photos is usually dozens of times higher than that of onload. However, for normal web (within 800 × 600) browsing-level images, the effect of flash can be achieved.
Well, please watch the pleasant DEMO. Tested browsers: Chrome, Firefox, Safari, Opera, IE6, IE7, and IE8.
Original link: http://www.planeart.cn /? P = 1121