Track Image Loading effect code analysis

Source: Internet
Author: User

Purpose
During the image loading process, a callback function is provided to define whether the image is loaded successfully or fails to load/times out, and the function is executed.

Motivation
Native JavaScript has provided onload and onerror registration events for Image objects. However, due to browser caching and other factors, the onload event is often not triggered stably when you use the rollback button or refresh the page. In my developed album system, I want images to be displayed according to the custom size to avoid page deformation. For example, the maximum width cannot exceed PX, and images smaller than PX width are displayed in the original size. CSS2 provides the max-width attribute to help groups achieve this goal. Unfortunately, ie6.


IE6 registers the img. onload event to automatically resize the image after it is loaded. The following code is taken from the famous Discuz! Processing of display images in forum system 4.1.


Onload = "if (this. width> screen. width * 0.7) {this. resized = true; this. width = screen. width * 0.7;
This. alt = 'click here to open new javaswnctrl + Mouse wheel to zoom in/out ';}"
Onmouseover = "if (this. width> screen. width * 0.7) {this. resized = true; this. width = screen. width * 0.7; this. style. cursor = 'hand'; this. alt = 'click here to open new javaswnctrl + Mouse wheel to zoom in/out ';}"
Onclick = "if (! This. resized) {return true;} else {window. open ('HTTP: // www.bkjia.com/uploads/allianz 131015/20522952y-0.jpg ');}"
Onmousewheel = "return imgzoom (this);">

As mentioned above, the browser does not guarantee the execution of event processing functions. Therefore, we need a more stable way to track the image loading process and execute the set callback function.

Implementation
The image. complete attribute indicates the image loading status. If the value is true, the image is loaded successfully. If the image does not exist or the loading times out, the value is false. You can use the setInterval () function to regularly check the image loading status. The code snippet is as follows:



ImageLoader = Class. create ();
ImageLoader. prototype = {
Initialize: function (options ){
This. options = Object. extend ({
Timeout: 60, // 60 s
OnInit: Prototype. emptyFunction,
OnLoad: Prototype. emptyFunction,
OnError: Prototype. emptyFunction
}, Options | {});
This. images = [];
This. pe = new PeriodicalExecuter (this. _ load. bind (this), 0.02 );
},
........
}

Use the Prototype PeriodicalExecuter class to create a timer, check the image loading status every 20 milliseconds, and execute the callback function defined in the options parameter according to the status.

Use



Var loader = new ImageLoader ({
Timeout: 30,
OnInit: function (img ){
Img. style. width = '100px ';
},
OnLoad: function (img ){
Img. style. width = '';
If (img. width & gt; 500)
Img. style. width = '500px ';
},
OnError: function (img ){
Img. src = 'error.jpg '; // hint image
}
}); Loader. loadImage (document. getElementsByTagName ('img '));

The code above defines that the image is initially displayed in PX. After the image is loaded successfully, if the actual width of the image exceeds PX, It is forcibly defined as PX; otherwise, the original size is displayed. If the image does not exist or the loading times out (30 seconds for timeout), an error image is displayed.

Similarly, you can use the ImageLoader callback function to customize the effects as needed. For example, the default loading function is displayed, and the source image is displayed after the loading is complete. The grayscale display is used for the image first, and the brightness is restored after the loading is complete. For example:



// Need scriptaculous effects. js
Var loader = new ImageLoader ({
OnInit: function (img ){
Element. setOpacity (img, 0.5); // Level 5 transparency by default
},
OnLoad: function (img ){
Effect. Appear (img); // restore the source Image
}
});


The attached example contains the complete code and uses the pconline image for testing. Note that the latest Prototype 1.5.0 _ rc1 is used in the example.

<! Doctype html public "-// W3C // dtd html 4.0 // EN">
<Html>
<Head>
<Script src = "prototype1.5.0 _ rc1.js"> </script>
<Script src = "validation1.5.3/effects. js"> </script>
</Head>

<Body>






<Br/> test of loading failure <br/>



<Script type = "text/javascript">
ImageLoader = Class. create ();
ImageLoader. prototype = {

Initialize: function (options ){
This. options = Object. extend ({
Timeout: 60, // 60 s
OnInit: Prototype. emptyFunction,
OnLoad: Prototype. emptyFunction,
OnError: Prototype. emptyFunction
}, Options | {});
This. images = [];
This. pe = new PeriodicalExecuter (this. _ load. bind (this), 0.02 );
},

LoadImage: function (){
Var self = this;
$ A (arguments). each (function (img ){
If (typeof (img) = 'object ')
$ A (img). each (self. _ addImage. bind (self ));
Else
Self. _ addImage (img );
});
},

_ AddImage: function (img ){
Img = $ (img );
Img. onerror = this. _ onerror. bind (this, img );
This. options. onInit. call (this, img );
If (this. options. timeout> 0 ){
SetTimeout (this. _ ontimeout. bind (this, img), this. options. timeout * 1000 );
}
This. images. push (img );
If (! This. pe. timer)
This. pe. registerCallback ();
},


_ Load: function (){
This. images = this. images. select (this. _ onload. bind (this ));
If (this. images. length = 0 ){
This. pe. stop ();
}
},

_ CheckComplete: function (img ){
If (img. _ error ){
Return true;
} Else {
Return img. complete;
}
},

_ Onload: function (img ){
If (this. _ checkComplete (img )){
This. options. onLoad. call (this, img );
Img. onerror = null;
If (img. _ error)
Try {delete img. _ error} catch (e ){}
Return false;
}
Return true;
},

_ Onerror: function (img ){
Img. _ error = true;
Img. onerror = null;
This. options. onError. call (this, img );
},

_ Ontimeout: function (img ){
If (! This. _ checkComplete (img )){
This. _ onerror (img );
}
}

}

Var loader = new ImageLoader ({
Timeout: 30,
OnInit: function (img ){
Img. style. width = '100px ';
},
OnLoad: function (img ){
Img. style. width = '';
If (img. width> 500 ){
Img. style. width = '500px ';
}
},
OnError: function (img ){
Img. src = 'HTTP: // img.pconline.com.cn/nopic.gif ';
}
});

Loader. loadImage (document. getElementsByTagName ('img '));

/*
Var loader = new ImageLoader ({
Timeout: 30,
OnInit: function (img ){
Element. setOpacity (img, 0.5 );
},
OnLoad: function (img ){
Effect. Appear (img );
},
OnError: function (img ){
Img. src = 'HTTP: // img.pconline.com.cn/nopic.gif ';
}
});
*/

/*
$ A (document. getElementsByTagName ('img '). each (
Function (img ){
Img. onload = function (){
Img. style. width = '300px ';
}
}
);
*/

</Script>
</Body>
</Html>

Related Article

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.