When working on h5 mobile pages, I believe you must have encountered a situation where the page has been opened, but the images inside have not been loaded. Although this problem does not affect the function of the page, it is not conducive to the user experience. Regardless of the network speed, there are many ways to solve this problem: the most basic one is to optimize performance from aspects such as http request merging, cache management, image compression, etc.; the other is to pre-process all images used in the page. In the loading process, when the user opens the page, the first screen is not displayed immediately. Instead, the resource loading effect is displayed first, and then the main content of the page is displayed after the loading is completed. This can solve the problem. Although this loading effect takes up the user's browsing time, we can make it more beautiful and interesting, so it will not affect the user experience. This article implements this idea and provides a very simple image preloading component, which is simple to implement and not weak in function. It should be of reference value to you when making mobile pages.
Effect:
##1. Implementation ideas
The img tag in html and background-imag in css will trigger the browser to load the related image, but if the image has already been loaded, the browser will use this image directly. The loaded image can be instantly rendered on the page. Through javascript, create Image objects, and then set the src attribute of these objects to the address of the image to be loaded, which can also trigger the browser to load the image. You can use this to realize the image preloading function: first use the relevant information on the page. Hide the elements of the image, then use js to load the image, wait until all images are loaded, and then display the hidden elements. However, this is just a basic implementation idea. To complete a preloading component with a more robust function, there are still three problems:1) Progress problem
Due to preloading, a preloading must be done at the same time The effect is that the loading progress needs to be notified to the external context in real time. There are two ways to implement progress. The first is the loaded data size/total data size, and the second is the number of loaded files/total number of files. In the browser, it is unrealistic to use the first method. , there is no native way to do it, so we can only use the second method.
2) Image loading failure problem
For example, if there are 4 images, 50% of them have been loaded, and an error occurs when loading the third image. Should the progress be fed back to 75%? The answer is: yes. If this is not done, the progress will never reach 100%, and the main content of the page will have no chance to be displayed. Although the image loading may fail, it has nothing to do with the loader. Maybe the image itself does not exist? This means that failure to load images should not affect the functionality of the loader.
3) Image loading timeout problem
The image cannot be loaded for too long, otherwise the user will stay in the loading effect and cannot see the main content, and the user's waiting time will be extended uncontrollably, resulting in a decline in user experience, so there will be It goes against the original intention of the loader. Therefore, a loading timeout should be set for each image. If the loading has not been completed after the timeout of all images, the loading should be actively abandoned, the external context should be notified that the loading is complete, and the main content should be displayed.
Based on the above requirements, the implementation provided in this article is:
JavaScript CodeCopy content to the clipboard
(function () { function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * @param imgList 要加载的图片地址列表,['aa/asd.png','aa/xxx.png'] * @param callback 每成功加载一个图片之后的回调,并传入“已加载的图片总数/要加载的图片总数”表示进度 * @param timeout 每个图片加载的超时时间,默认为5s */ 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]; } /** * 如果timeout * total时间范围内,仍有图片未加载出来(判断条件是loaded < total),通知外部环境所有图片均已加载 * 目的是避免用户等待时间过长 */ setTimeout(function () { loaded < total && (loaded = total, callback && callback(loaded / total)); }, timeout * total); }; "function" === typeof define && define.cmd ? define(function () { return loader }) : window.imgLoader = loader; })();
Copy content 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>
Run result:
2. demo说明
本文开篇给出的效果,对应的页面是index.html,关于这个效果还有两个问题需要说明:
1)它用了之前这篇博客Hammer.js+轮播原理实现简洁的滑屏功能介绍的滑屏思路,并把它的一些逻辑包装在了swipe.js,对外提供了一个全局变量Swipe,这个模块有一个init的方法,以便外部通过调用Swipe.init()就能初始化滑屏相关的功能,原来没有提供这个init方法,在js加载完毕就会初始化滑屏功能,有了这个init方法就可以把滑屏的逻辑延迟到加载完毕的时候去初始化。index.html一共引用了5个js:
XML/HTML Code复制内容到剪贴板
<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>
其中imgLoader.js就是前面介绍图片加载器的实现,前三个js都是为最后一个swipe.js服务的,感兴趣的可以继续我的博客利用轮播原理结合hammer.js实现简洁的滑屏功能了解相关内容。不过滑屏不是本文的重点,不了解swipe.js不会影响理解本文的内容~
2)虽然我在demo中用到了3张比较大的图片,但是由于在本地环境,加载速度还是非常快,所以一开始的时候,很难看到预加载的效果,最后只能想办法在每个进度回调之前做一下延迟,这才可以看到前面gif图片一开始的那个loading效果,实现方式是:
XML/HTML Code复制内容到剪贴板
//模拟加载慢的效果 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; $('#loader__info').html('Loading ' + (parseInt(percentT)) + '%'); $('#loader__progress')[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](); } });
在真实环境,最好还是不要刻意去加这种延迟,没必要为了让用户看到一个好看有趣的加载效果,就浪费它不必要的等待时间,所以真实环境还是应该用下面的代码:
XML/HTML Code复制内容到剪贴板
imgLoader(['img/page1.jpg', 'img/page2.jpg', 'img/page3.jpg'], function (percentage) { var percentT = percentage * 100; $('#loader__info').html('Loading ' + (parseInt(percentT)) + '%'); $('#loader__progress')[0].style.width = percentT + '%'; if (percentage == 1) { $('#loader').remove(); Swipe.init(); } });
3. 注意事项
预加载是一种比较常见的实现效果,但是在使用的时候,有些问题需要注意:
1)什么时候用
页面大的时候用,一般页面大小超过3M就该考虑使用;页面内包含数据量比较大的图片,在手机端测试能够明显看到加载缓慢的时候,可以考虑使用。
2)尽量使用sprite图片
3)加载效果实现的时候,尽量不用图片,即使要用也应该用很小的图片,否则加载效果卡在那就没有意义了。
4. 总结
本文主要介绍了一个简单的图片预加载器,可应用于h5移动页面的开发当中,在它的思路之下,如果有必要的话,还可以对它进行一些改造,用它来加载其它类型的资源,比如音频或者视频文件,毕竟这些类型的DOM对象也都有提供类似Image对象的属性和回调。与预加载的方式相反的,还有一种图片懒加载的技术,现在网上已经有比较好用的jquery插件了,不过还是很值的去深入了解下它的思路跟实现要点,等我有时间去研究研究。同时感谢大家一直以来对PHP中文网的支持!
更多利用简洁的图片预加载组件提升html5移动页面的用户体验 相关文章请关注PHP中文网!