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
- (Function (){
- Function isArray (obj ){
- Return Object. prototype. toString. call (obj) = '[object Array]';
- }
- /**
- * @ Param imgList: List of image addresses to be loaded, ['aa/asd.png ', 'aa/xxx.png']
- * @ 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
- * @ Param timeout the time-out for loading each image. The default value is 5 s.
- */
- Var loader = function (imgList, callback, timeout ){
- Timeout = timeout | 5000;
- ImgList = isArray (imgList) & imgList | [];
- Callback = typeof (callback) === 'function' & callback;
- Var total = imgList. length,
- Loaded = 0,
- Imgages = [],
- _ On = function (){
- Loaded <total & (++ loaded, callback & callback (loaded/total ));
- };
- If (! Total ){
- Return callback & callback (1 );
- }
- For (var I = 0; I <total; I ++ ){
- Imgages [I] = new Image ();
- Imgages [I]. onload = imgages [I]. onerror = _ on;
- Imgages [I]. src = imgList [I];
- }
- /**
- * 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.
- * The purpose is to prevent users from waiting too long.
- */
- SetTimeout (function (){
- Loaded <total & (loaded = total, callback & callback (loaded/total ));
- }, Timeout * total );
- };
- "Function" === typeof define & define. cmd? Define (function (){
- Return loader
- }): Window. imgLoader = loader;
- })();
Use the formula (test.html in the Code ):
Copy XML/HTML Code to clipboard
- <Script src = "../js/imgLoader. js"> </script>
- <Script>
- ImgLoader (['../img/page1.jpg', '../img/page2.jpg', '../img/page3.jpg'], function (percentage ){
- Console. log (percentage)
- });
- </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
- <Script src = "js/zepto. js"> </script>
- <Script src = "js/transition. js"> </script>
- <Script src = "js/hammer. js"> </script>
- <Script src = "js/imgLoader. js"> </script>
- <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
- // Simulate slow loading
- Var callbacks = [];
- ImgLoader (['img/page1.jpg ', 'img/page2.jpg', 'img/page3.jpg '], function (percentage ){
- Var I = callbacks. length;
- Callbacks. push (function (){
- SetTimeout (function (){
- Var percentT = percentage * 100;
- Response ('{loader=info'{.html ('loading' + (parseInt (percentT) + '% ');
- $ ('# Loader _ SS') [0]. style. width = percentT + '% ';
- If (percentage = 1 ){
- SetTimeout (function (){
- $ ('# Loader'). remove ();
- Swipe. init ();
- },600 );
- }
- Callbacks [I + 1] & callbacks [I + 1] ();
- },600 );
- });
- If (percentage = 1 ){
- Callbacks [0] ();
- }
- });
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
- ImgLoader (['img/page1.jpg ', 'img/page2.jpg', 'img/page3.jpg '], function (percentage ){
- Var percentT = percentage * 100;
- Response ('{loader=info'{.html ('loading' + (parseInt (percentT) + '% ');
- $ ('# Loader _ SS') [0]. style. width = percentT + '% ';
- If (percentage = 1 ){
- $ ('# Loader'). remove ();
- Swipe. init ();
- }
- });
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!