Home Web Front-end JS Tutorial Jquery promise implements loading images one by one_jquery

Jquery promise implements loading images one by one_jquery

May 16, 2016 pm 03:32 PM

Promise is one of the specifications of CommonJS. It has resolve, reject, done, fail, then and other methods, which can help us control the flow of code and avoid multi-layer nesting of functions. Nowadays, asynchrony is becoming more and more important in web development. For developers, this kind of non-linear execution programming will make it difficult for developers to control. Promise can allow us to better control the execution process of the code. Popular js such as jQuery All libraries have already implemented this object, and ES6, which will be released at the end of the year, will also natively implement Promise.

In the proxy mode of JavaScript design pattern practice - image preloading, the image preloading function is implemented using the proxy mode.

Now let’s go one step further and complete a function that can load continuous pictures one by one.

Function:

1. Load pictures one by one.

2. Loading error, the loading failure image will be displayed after timeout.

Regarding functional requirements, there will definitely be processing of loading status events and callback functions when completed. This will not only cause confusion in the code, but even destroy various principles, so we will no longer use ordinary methods to write it. . In view of the characteristics of this status notification, it is more suitable to use the promise architecture for processing. Promise is essentially a kind of subscription-publish design pattern. Currently, this function is developed using the promise that comes with jquery.

1. Complete a proxy creation function for loading images, which can generate a proxy with loading timeout, failure, success, and cancellation monitoring capabilities.

 function createLoadImgProxy(){
  var imgCache = new Image();
  var dfd = $.Deferred();
  var timeoutTimer;
  //开始加载超时监控,超时后进行reject操作
  function beginTimeoutWatcher(){
   timeoutTimer = setTimeout(function(){
   dfd.reject('timeout');
   }, 10000);
  }
  //结束加载超时监控
  function endTimeoutWatcher(){
   if(!timeoutTimer){
   return;
   }
   clearTimeout(timeoutTimer);
  }
  //加载完成事件处理,加载完成后进行resolve操作
  imgCache.onload = function(){
   dfd.resolve(this.src);
  };
  //加载终止事件处理,终止后进行reject操作
  imgCache.onabort = function(){
   dfd.reject("aborted");
  };
  //加载异常事件处理,异常后进行reject操作
  imgCache.onerror = function(){
   dfd.reject("error");
  };
  return function(eleImg, src){
   dfd.always(function(){
   //加载完成或加载失败都要终止加载超时监控
   endTimeoutWatcher();
   }).done(function(src){
   //加载完成后,往图片元素上设置图片
   loadImg(eleImg, src);
   }).fail(function(msg){
   //加载失败后,往图片元素上设置失败图片
   loadImg(eleImg, 'loadFailed.jpg');
   });
   loadImg(eleImg, 'loading.gif');
   imgCache.src = src;
   //开始进行超时加载监控
   beginTimeoutWatcher();
   return dfd.promise();
  };
  }
Copy after login

Among them, a Deferred object is created in the following way

Copy code The code is as follows:

var dfd = $.Deferred();

The Deferred object triggers the completion event through the resolve method and responds to the completion event using the done method.

Complete event when loading is successful.

Copy code The code is as follows:

imgCache.onload = function(){
                  dfd.resolve(this.src);
                };

and the response processing when loading is completed are to set the image to the element. The following code is a disassembly of the above chain writing method.

Copy code The code is as follows:

dfd.done(function(src){
//After loading is completed, set the image on the image element
LoadImg(eleImg, src);
                     });

The Defferred object triggers a rejection event through the reject method, and uses the fail method to respond to the rejection event, indicating that the loading failed.

Reject events when loading timeout, termination, exception.                                                                       

 //开始加载超时监控,超时后进行reject操作
  function beginTimeoutWatcher(){
   timeoutTimer = setTimeout(function(){
   dfd.reject('timeout');
   }, 10000);
  }
  //加载终止事件处理,终止后进行reject操作
  imgCache.onabort = function(){
   dfd.reject("aborted");
  };
  //加载异常事件处理,异常后进行reject操作
  imgCache.onerror = function(){
   dfd.reject("error");
  };
Copy after login
And response processing when loading fails, setting failure pictures.                                                          


 dfd.fail(function(msg){
   //加载失败后,往图片元素上设置失败图片
   loadImg(eleImg, 'loadFailed.jpg');
   });
Copy after login
At the end of the proxy function, return the deferred promise object, which is used to monitor the completion and failure status of the loading to the calling place to facilitate the loading of the next image.

return dfd.promise();


2. Continuous loading one by one

//一张一张的连续加载图片
  //参数:
  // srcs: 图片路径数组
  function doLoadImgs(srcs){
  var index = 0;
  (function loadOneByOne(){
   //退出条件
   if(!(s = srcs[index++])) {
   return;
   }
   var eleImg = createImgElement();
   document.getElementById('imgContainer').appendChild(eleImg);
   //创建一个加载代理函数
   var loadImgProxy = createLoadImgProxy();
   //在当前图片加载或失败后,递归调用,加载下一张
   loadImgProxy(eleImg, s).always(loadOneByOne);
  })();
  }
Copy after login
Make a recursive loading function of loadOneByOne.

A loading agent is first created internally. After the agent loads the image, regardless of success or failure, the loadOneByOne function is called recursively to load the next image.

The key lies in the promise object returned by the proxy function. Use the .always method to make a recursive call to loadOneByOne to load the next picture after the loading is completed (success or failure).

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

至此完成。

采用了promise模式后,callback函数不见了,维护状态的函数和内部变量也不见了,代码更清晰简单,使得代理函数和本地函数之间的一致性得到保护。

完整代码:

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8">
 </head>
 <body>
 <button id='btnLoadImg'>加载图片</button>
 <br>
 <div id='imgContainer'>
 </div>
 <br>
 <script type='text/javascript' src="./jquery-1.11.3.min.js"></script>
 <script type='text/javascript'>
  var imgSrcs = [
  'http://img.wanchezhijia.com/A/2015/3/20/17/11/de63f77c-f74f-413a-951b-5390101a7d74.jpg',
  'http://www.newbridgemotorsport.com/files/6413/9945/0406/IMG_3630.jpg',
  'http://www.carsceneuk.com/wp-content/uploads/2015/03/88y9989.jpg',
  'http://mfiles.sohu.com/20130223/5ff_403b2e7a_7a1f_7f24_66eb_79e3f27d58cf_1.jpg',
  'http://img1.imgtn.bdimg.com/it/u=2678963350,1378052193&fm=21&gp=0.jpg'
  ];
  $(document).ready(function(){
  $('#btnLoadImg').bind('click', function(){
   doLoadImgs(imgSrcs);
  });
  });
  //创建img标签
  //这里用自执行函数加一个闭包,是为了可以创建多个id不同的img标签。
  var createImgElement = (function(){
  var index = 0;
  return function() {
   var eleImg = document.createElement('img');
   eleImg.setAttribute('width', '200');
   eleImg.setAttribute('heght', '150');
   eleImg.setAttribute('id', 'img' + index++);
   return eleImg;
  };
  })();
  function loadImg(img, src) {
  img.src = src;
  }
  function createLoadImgProxy(){
  var imgCache = new Image();
  var dfd = $.Deferred();
  var timeoutTimer;
  //开始加载超时监控,超时后进行reject操作
  function beginTimeoutWatcher(){
   timeoutTimer = setTimeout(function(){
   dfd.reject('timeout');
   }, 10000);
  }
  //结束加载超时监控
  function endTimeoutWatcher(){
   if(!timeoutTimer){
   return;
   }
   clearTimeout(timeoutTimer);
  }
  //加载完成事件处理,加载完成后进行resolve操作
  imgCache.onload = function(){
   dfd.resolve(this.src);
  };
  //加载终止事件处理,终止后进行reject操作
  imgCache.onabort = function(){
   dfd.reject("aborted");
  };
  //加载异常事件处理,异常后进行reject操作
  imgCache.onerror = function(){
   dfd.reject("error");
  };
  return function(eleImg, src){
   dfd.always(function(){
//   alert('always end');
   //加载完成或加载失败都要终止加载超时监控
   endTimeoutWatcher();
   }).done(function(src){
//   alert('done end');
   //加载完成后,往图片元素上设置图片
   loadImg(eleImg, src);
   }).fail(function(msg){
//   alert('fail end:' + msg);
   //加载失败后,往图片元素上设置失败图片
   loadImg(eleImg, 'loadFailed.jpg');
   });
   loadImg(eleImg, 'loading.gif');
   imgCache.src = src;
   //开始进行超时加载监控
   beginTimeoutWatcher();
   return dfd.promise();
  };
  }
  //一张一张的连续加载图片
  //参数:
  // srcs: 图片路径数组
  function doLoadImgs(srcs){
  var index = 0;
  (function loadOneByOne(){
   //退出条件
   if(!(s = srcs[index++])) {
   return;
   }
   var eleImg = createImgElement();
   document.getElementById('imgContainer').appendChild(eleImg);
   //创建一个加载代理函数
   var loadImgProxy = createLoadImgProxy();
   //在当前图片加载或失败后,递归调用,加载下一张
   loadImgProxy(eleImg, s).always(loadOneByOne);
  })();
  }
 </script>
 </body>
</html>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles