Jquerypromise implements one piece of loading image _ jquery-js tutorial

Source: Internet
Author: User
Jquerypromise is used to load a continuous image. When an image loading error occurs, the loading of the image fails. If you are interested in using jquerypromise to load images, refer to Promise, which is one of the CommonJS specifications and has methods such as resolve, reject, done, fail, and then, it helps us control the code process and avoid multi-layer nesting of functions. Nowadays, Asynchronization is becoming more and more important in web development. for developers, this kind of non-linear execution programming makes developers feel difficult to control, and Promise allows us to better control the code execution process, jQuery and other popular js libraries have implemented this object. ES6, which will be released at the end of the year, will also implement Promise native.

In the javascript design mode, the proxy mode is used to implement the image pre-loading function in the proxy mode.

Now let's move on to complete the function of loading a continuous image.

Function:

1. Load an image one by one.

2. An error occurred while loading. An error occurred while loading the image.

For functional requirements, there will certainly be processing loading status events and processing of callback functions at completion, which will not only cause code confusion, but even undermine various principles, it will no longer be written using common methods. In view of the characteristics of such status notifications, it is appropriate to use the promise architecture for processing. promise is essentially a type of subscription release design mode. Currently, this function is developed using the promise provided by jquery.

1. Complete a proxy creation function for image loading to generate a proxy with loading timeout, failure, success, and unmonitoring capabilities.

Function createLoadImgProxy () {var imgCache = new Image (); var dfd = $. deferred (); var timeoutTimer; // start loading timeout monitoring. After timeout, perform the reject operation function beginTimeoutWatcher () {timeoutTimer = setTimeout (function () {dfd. reject ('timeout') ;}, 10000) ;}// end loading timeout monitoring function endTimeoutWatcher () {if (! TimeoutTimer) {return;} clearTimeout (timeoutTimer);} // completes loading event processing. After loading is complete, resolve the imgCache operation is performed. onload = function () {dfd. resolve (this. src) ;}; // handle the load termination event, and perform the reject operation imgCache. onabort = function () {dfd. reject ("aborted") ;}; // load exception event processing. After an exception occurs, perform the reject operation imgCache. onerror = function () {dfd. reject ("error") ;}; return function (eleImg, src) {dfd. always (function () {// If loading is complete or loading fails, Stop loading timeout monitoring endTimeoutWatcher ();}). done (function (src) {// after loading, set the loadImg (eleImg, src);}) on the Image Element );}). fail (function (msg) {// after loading fails, set loadImg (eleImg, 'loadFailed.jpg ');}); loadImg (eleImg, 'loading.gif '); imgCache. src = src; // start timeout Loading Monitoring beginTimeoutWatcher (); return dfd. promise ();};}

A Deferred object is created using the following methods:

The Code is as follows:


Var dfd = $. Deferred ();

The Deferred object triggers the completion event using the resolve method, and uses the done method to respond to the completion event.

The completion event when the load is successful.

The Code is as follows:


ImgCache. onload = function (){
Dfd. resolve (this. src );
};

And the response processing when the loading is complete, is to set the image to the element, the following code is the disassembly of the chain writing above.

The Code is as follows:


Dfd. done (function (src ){
// After loading, set the image to the Image Element
LoadImg (eleImg, src );
});


The Defferred object triggers a rejection event using the reject method. The fail method is used to respond to the rejection event, indicating that the loading failed.

A rejection event when loading times out, stops, or encounters an exception.

// Start loading timeout monitoring. After timeout, perform the reject operation function beginTimeoutWatcher () {timeoutTimer = setTimeout (function () {dfd. reject ('timeout') ;}, 10000) ;}// handle the load termination event, and then perform the reject operation imgCache. onabort = function () {dfd. reject ("aborted") ;}; // load exception event processing. After an exception occurs, perform the reject operation imgCache. onerror = function () {dfd. reject ("error ");};

And the response processing when loading fails, set the failure image.

Dfd. fail (function (msg) {// after loading fails, set loadImg (eleImg, 'loadFailed.jpg ') for the failed image element ');});

At the end of the proxy function, the deferred promise object is returned, which is used to monitor the loading completion and failure state for the called place, so that the next image can be loaded.

Return dfd. promise ();

2. One piece of continuous Loading

// Load the image one by one. // parameter: // srcs: function doLoadImgs (srcs) {var index = 0; (function loadOneByOne () {// exit condition if (! (S = srcs [index ++]) {return;} var eleImg = createImgElement (); document. getElementById ('imginer iner '). appendChild (eleImg); // create a loading proxy function var loadImgProxy = createLoadImgProxy (); // recursively call the current image after it fails to be loaded or load the next loadImgProxy (eleImg, s ). always (loadOneByOne );})();}

Create a loadOneByOne load recursion function.

Create an internal loading agent. Call the loadOneByOne function recursively to load the next image after the agent loads the image.

The key lies in the promise object returned by the proxy function. The. always method can be used to load the next one after loadOneByOne is loaded (successful or failed) recursively.

The Code is as follows:


LoadImgProxy (eleImg, s). always (loadOneByOne );

So far.

After the promise mode is adopted, the callback function is gone, the function for maintaining the status and the internal variables are gone, and the code is clearer and simpler, so that the consistency between the proxy function and the local function is protected.

Complete code:

  
    Attach Images 


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.