Improve the user experience of html5 mobile pages by using simple image pre-loading components,

Source: Internet
Author: User

Improve the user experience of html5 mobile pages by using simple image pre-loading components,

I believe that the page has already been opened but the images in it have not been loaded. This problem does not affect the page function, but is not conducive to the user experience. Aside from the causes of network speed, there are many ways to solve this problem: the most basic thing is to optimize the performance of http request merging, Cache Management, and image compression; in addition, you can pre-load all the images used in the page. When you open the page, the first screen is not displayed immediately, but the resource loading effect is displayed first, then display the main content of the page to solve the problem. Although this loading effect takes the user's browsing time, we can make it interesting, so it will not affect the user experience. This article has put this idea into practice and provides a very concise picture pre-loading component, which is simple to implement and has no weak functionality. It should be of reference value to you when you are doing mobile pages.
Effect:

1. Implementation ideas

The img tag in html and the background-imag in css will trigger the browser to load the relevant image. However, if the image has already been loaded, the browser will directly use this loaded image to render it instantly on the page. Using javascript to create an Image object and set the src attribute of these objects to the Image address to be loaded can also trigger the browser to load the Image. This can be used to implement the Image pre-loading function: on the page, first hide the elements that use the relevant images, then use js to load the images, and then display the hidden elements after loading all the images. However, this is just a basic implementation idea. To complete a robust pre-loaded component, there are three problems:
1) Progress Problems
Because the pre-loading has to be performed at the same time, the loading progress must be notified to the external context in real time. There are two ways to implement the progress: the first is the size of the loaded data/The total size of the data, and the second is the number of loaded files/the total number of files, in the browser, the first method is unrealistic, and there is no native way to do it. Therefore, the second method can only be used.
2) image loading failure
For example, if four images have already been loaded with 50% images and an error occurred while loading the third image, shouldn't the progress be fed back to 75%? The answer is: yes. If this is not done, the progress will never reach 100%, and the page's main content will not be displayed. Although the image loading fails, it has nothing to do with the loader, maybe the image itself does not exist? That is to say, image loading failure should not affect the function of the loader.
3) image loading timeout
Images cannot be loaded for too long. Otherwise, the user will not be able to see the main content in the loading effect, and the user's waiting time will be extended unlimitedly, resulting in a decline in user experience. This is contrary to the original intention of the loader. Therefore, you should set a loading time-out period for each image. If loading is not completed after the time-out period of all images, you should take the initiative to stop loading and notify the external context to load, displays the main content.
Based on the above requirements, this article provides the following implementation:

Copy the content to the clipboard using JavaScript Code
  1. (Function (){
  2. Function isArray (obj ){
  3. Return Object. prototype. toString. call (obj) = '[object Array]';
  4. }
  5. /**
  6. * @ Param imgList: List of image addresses to be loaded, ['aa/asd.png ', 'aa/xxx.png']
  7. * @ Param callback refers to the progress after each successful loading of an image, and input "Total number of Loaded Images/total number of images to be loaded" to indicate the progress
  8. * @ Param timeout the time-out for loading each image. The default value is 5 s.
  9. */
  10. Var loader = function (imgList, callback, timeout ){
  11. Timeout = timeout | 5000;
  12. ImgList = isArray (imgList) & imgList | [];
  13. Callback = typeof (callback) === 'function' & callback;
  14. Var total = imgList. length,
  15. Loaded = 0,
  16. Imgages = [],
  17. _ On = function (){
  18. Loaded <total & (++ loaded, callback & callback (loaded/total ));
  19. };
  20. If (! Total ){
  21. Return callback & callback (1 );
  22. }
  23. For (var I = 0; I <total; I ++ ){
  24. Imgages [I] = new Image ();
  25. Imgages [I]. onload = imgages [I]. onerror = _ on;
  26. Imgages [I]. src = imgList [I];
  27. }
  28. /**
  29. * If an image is still not loaded within the timeout * total time range (the condition is loaded <total), it indicates that all images in the external environment have been loaded.
  30. * The purpose is to prevent users from waiting too long.
  31. */
  32. SetTimeout (function (){
  33. Loaded <total & (loaded = total, callback & callback (loaded/total ));
  34. }, Timeout * total );
  35. };
  36. "Function" === typeof define & define. cmd? Define (function (){
  37. Return loader
  38. }): Window. imgLoader = loader;
  39. })();

Use the formula (test.html in the Code ):

Copy XML/HTML Code to clipboard
  1. <Script src = "../js/imgLoader. js"> </script>
  2. <Script>
  3. ImgLoader (['../img/page1.jpg', '../img/page2.jpg', '../img/page3.jpg'], function (percentage ){
  4. Console. log (percentage)
  5. });
  6. </Script>

Running result:


2. demo description
The effect of this article is index.html. There are two questions about this effect:
1) it uses the previous blog Hammer. js + carousel Implementation of simple sliding screen function introduction of Sliding Screen ideas, and some of its logic is packaged in swipe. js, which provides a global variable Swipe. This module has an init method to call Swipe externally. init () can initialize Sliding Screen functions. This init method is not provided in the past. After loading js, the sliding screen function will be initialized, with this init method, the logic of the sliding screen can be delayed until Initialization is completed. Index.html references a total of five js files:

Copy XML/HTML Code to clipboard
  1. <Script src = "js/zepto. js"> </script>
  2. <Script src = "js/transition. js"> </script>
  3. <Script src = "js/hammer. js"> </script>
  4. <Script src = "js/imgLoader. js"> </script>
  5. <Script src = "js/swipe. js"> </script>

Here, imgLoader. js is the implementation of the previously introduced image loader. The first three js are the last swipe. js service. If you are interested, you can continue to use the carousel principle in combination with hammer. js implements simple Sliding Screen functions to learn more. However, sliding screens are not the focus of this Article. Failing to understand swipe. js will not affect understanding the content of this article ~
2) Although I used three large images in the demo, the loading speed was very fast in the local environment, so at the beginning, it is difficult to see the effect of the pre-loading. In the end, you can only find a way to perform a delay before each progress callback, so that you can see the loading effect from the beginning of the GIF image. The implementation method is as follows:

Copy XML/HTML Code to clipboard
  1. // Simulate slow loading
  2. Var callbacks = [];
  3. ImgLoader (['img/page1.jpg ', 'img/page2.jpg', 'img/page3.jpg '], function (percentage ){
  4. Var I = callbacks. length;
  5. Callbacks. push (function (){
  6. SetTimeout (function (){
  7. Var percentT = percentage * 100;
  8. Response ('{loader=info'{.html ('loading' + (parseInt (percentT) + '% ');
  9. $ ('# Loader _ SS') [0]. style. width = percentT + '% ';
  10. If (percentage = 1 ){
  11. SetTimeout (function (){
  12. $ ('# Loader'). remove ();
  13. Swipe. init ();
  14. },600 );
  15. }
  16. Callbacks [I + 1] & callbacks [I + 1] ();
  17. },600 );
  18. });
  19. If (percentage = 1 ){
  20. Callbacks [0] ();
  21. }
  22. });

In the real environment, it is best not to deliberately add such a delay. There is no need to waste unnecessary waiting time to let users see a nice and interesting loading effect, therefore, the following code should be used in the real environment:

Copy XML/HTML Code to clipboard
  1. ImgLoader (['img/page1.jpg ', 'img/page2.jpg', 'img/page3.jpg '], function (percentage ){
  2. Var percentT = percentage * 100;
  3. Response ('{loader=info'{.html ('loading' + (parseInt (percentT) + '% ');
  4. $ ('# Loader _ SS') [0]. style. width = percentT + '% ';
  5. If (percentage = 1 ){
  6. $ ('# Loader'). remove ();
  7. Swipe. init ();
  8. }
  9. });

3. Notes
Pre-loading is a common implementation effect, but when using it, you need to pay attention to the following issues:
1) when to use
When the page size is large, generally the page size exceeds 3 m should be considered for use; the page contains pictures with a large amount of data, the mobile phone side test can obviously see when loading is slow, you can consider using it.
2) use sprite images whenever possible
3) when loading effects, try not to use images. Even if you want to use a small image, otherwise loading effects will be meaningless.
4. Summary
This article mainly introduces a simple image preloader that can be used in the development of h5 mobile pages. Under its ideas, if necessary, it can also be transformed, it is used to load other types of resources, such as audio or video files. After all, these types of DOM objects also provide attributes and callbacks similar to Image objects. In contrast to the pre-loading method, there is also a lazy image loading technology, and now there is a relatively useful jquery plug-in on the internet, however, it is worthwhile to have a deep understanding of its ideas and Implementation points, and wait for me to study it. At the same time, I would like to thank you for your constant support for the help House website!

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.