关于loading加载的2个插件。
jQuery.lazyload
Echo.js
这两个插件功能都满足不了需求,我们这里只是因为图片加载比较慢,需要一个转圈而已,并不是需要懒加载。
而且,这两个插件也无法设置图片加载后的显示。
自己了写一个 效果展示:网速太快不太不明显哈哈
http://sunbrightness.gitee.io/csdn-material/img_loading/loading.html
原理:img标签不使用src进行资源加载。
使用 Image对象获取img标签上的src-data属性,进行加载,判断加载完成后回显。
<!doctype html><html> <head> <meta charset="UTF-8" /> <title>js图片未加载完显示loading效果</title> <style type="text/css"> img { width: 200px; height: 200px; margin: 0 10px 10px 0 } </style> <script> //判断浏览器 var Browser = new Object(); Browser.userAgent = window.navigator.userAgent.toLowerCase(); Browser.ie = /msie/.test(Browser.userAgent); Browser.Moz = /gecko/.test(Browser.userAgent); //判断是否加载完成 function Imagess (url, callback, error) { var val = url; var img = new Image(); if (Browser.ie) { img.onreadystatechange = function () { if (img.readyState == "complete" || img.readyState == "loaded") { callback(img); } } } else { img.onload = function () { if (img.complete == true) { callback(img); } } } //如果因为网络或图片的原因发生异常,则显示该图片 if (error) { img.onerror = error; } else { img.onerror = function () { img.src = "http://sunbrightness.gitee.io/csdn-material/img_loading/failed.png" } } img.src = val; } //进入页面既执行函数 window.onload = function () { img_loading(); } //初始化需要显示的图片,并且指定显示的位置 function img_loading () { var imglist = document.getElementsByTagName('img'); for (i = 0; i < imglist.length; i++) { let tt = imglist[i]; //防止重复加载 if (tt.loading == true) { continue; } //没有该属性代表不加载 if (!tt.getAttribute("src-data")) { continue; } tt.loading = true; tt.src = "http://sunbrightness.gitee.io/csdn-material/img_loading/loading.gif"; Imagess(tt.getAttribute("src-data"), function (obj) { tt.src = obj.src; tt.removeAttribute("src-data"); }); } } </script> </head> <body> <img src-data="http://sunbrightness.gitee.io/csdn-material/img_loading/57ddfd1edeb2b.jpg?raw=true" /> <img src-data="http://sunbrightness.gitee.io/csdn-material/img_loading/57ddfd1edeb2b.jpg?raw=true" /> <img src-data="http://sunbrightness.gitee.io/csdn-material/img_loading/57ddfd1edeb2b.jpg?raw=true" /> <hr/> <h1>加载失败</h1> <div> <img src-data="http://sunbrightness.gitee.io/csdn-material/?raw=true" /> </div> </body></html>还有一个有趣的loading素材网站
https://loading.io/