Track Image Loading effect code Analysis _javascript Skills

Source: Internet
Author: User
Tags extend
Objective
During the loading of the picture, provide a callback function that defines the success or failure/timeout of the picture when it is loaded, and ensures execution.

Motivation
Native JavaScript has provided the OnLoad and OnError registration events for the Image object. However, under the influence of browser caching and other factors, onload events often fail to trigger when users use the rollback button or refresh the page. In my photo album system, I want the pictures to be displayed according to the custom size to avoid page distortion, for example, the maximum width should not exceed 500px, and less than 500px width of the picture is displayed according to the original size. CSS2 provides the Max-width attribute to help group us achieve this goal. But unfortunately, the thousand-knife IE6 does not support.


IE6 a way to make up is by registering the Img.onload event to automatically resize the picture after it has finished loading. The following code is taken from the well-known discuz! forum system 4.1 version of the display image processing.


Onload= "if (this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;
this.alt= ' Click here to open new windownctrl+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 windownctrl+mouse wheel to Zoom in/out ';} '
Onclick= ' if (!this.resized) {return true;} else {window.open (' http://img8.imagepile.net/img8/47104p155.jpg ');} '
Onmousewheel= "return imgzoom (this);" >

As mentioned earlier, the browser does not guarantee that the event handler function executes. So you need a more stable way to track the image loading process and execute the set callback function.

Realize
The Image.complete property indicates a picture load state whose value, if ture, represents a successful load. False if picture does not exist or load timeout. Using the SetInterval () function to check this state periodically can realize the condition of tracking picture loading. The code snippet is as follows:



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

Use the prototype Periodicalexecuter class to create a timer that checks the picture's load every 20 milliseconds and executes the callback function defined in the options argument according to the state.

Use



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 = ' error.jpg '; Hint image
}
}); Loader.loadimage (document.getElementsByTagName (' img '));

The code above defines that the picture is initially displayed in 100px, and if the picture is actually wider than 500px after the load succeeds, then the definition is 500px, otherwise the original size is displayed. If the picture does not exist or the load timeout (30 seconds is timed out), an error picture is displayed.

Similarly, you can apply the Imageloader callback function to customize the effect according to the requirements, such as the default display loading, after loading and then display the original image, the picture first grayscale display, after the completion of loading and then restore brightness and so on. For example:



Need scriptaculous Effects.js
var loader = new Imageloader ({
Oninit:function (IMG) {
Element.setopacity (IMG, 0.5); Default Level 5 Transparency
},
Onload:function (IMG) {
Effect.appear (IMG); Restore Original display
}
});


The attached example contains the complete code and the test using the Pconline picture as an example, noting that the latest prototype 1.5.0_RC1 is used in the example.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//en" >
<script src= "Prototype1.5.0_rc1.js" ></script>
<script src= "Validation1.5.3/effects.js" ></script>

<body>






&LT;BR/> Load Failure test <br/>



<script type= "Text/javascript" >
Imageloader = Class.create ();
Imageloader.prototype = {

Initialize:function (options) {
This.options = Object.extend ({
Timeout:60,//60s
OnInit:Prototype.emptyFunction,
OnLoad:Prototype.emptyFunction,
OnError:Prototype.emptyFunction
}, Options | | {});
This.images = [];
this.pe = new Periodicalexecuter (the 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 = ' yun_qi_img/fdl.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 = ' yun_qi_img/fdl.gif ';
}
});
*/

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

</script>
</body>

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.