图片预加载的三种方法

it2022-05-09  36

lazyload插件

lazyload是jquer下的一个实现预加载的插件,cdn为:

http://apps.bdimg.com/libs/jquery-lazyload/1.9.5/jquery.lazyload.js

jquery的cdn:

http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js

  先引入文件

<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <script src="http://apps.bdimg.com/libs/jquery-lazyload/1.9.5/jquery.lazyload.js"></script>

  操作如下

$(function (){ $("img").lazyload({ placeholder:"./loading.gif", effect:"fadeIn", event:"mouseover" }) })

  placeholder是设置加载时的的loading图片

  effect是设置加载时的渐入效果

  event是采用什么事件触发加载,常用的是scroll mouseover click 等

  关于lazyload的更多知识,可以上官网查看  http://appelsiini.net/projects/lazyload/

<img data-original="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt="" class="lazy" > <img data-original="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt="" class="lazy" >

原生js

  其中传入参数必须为一个数组,数组里面存放的是图片的src

function preimg(arr){ var img=[], for(var i=0;i<arr.length;i++){ img[i]=new Image(); img[i].src=arr[i]; }

  

preimg(["http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg","http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg","http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg"])

  

<img src="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt=""> <img src="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt=""> <img src="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt=""> <img src="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt="">

    Image对象有两个常用的事件句柄,onload与onerror

ajax

  ajax预加载的原理就是,先加载图片文件的js和css,再给Image对象添加src,一共三个文件pre2.html preimgjs.js preimgcss.css

  pre2.html

<script > window.onload=function(){ setTimeout(function (){ var xhr=new XMLHttpRequest(); //js xhr.open("GET","./preimgjs.js"); xhr.send(null); //css var xhr2=new XMLHttpRequest(); xhr2.open("GET","./preimgcss.css"); xhr2.send(null); //img new Image().src = "http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg"; },1000); } </script> <body>   <img src="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" alt="">    </body>

   preimgjs.js

  

setTimeout(function (){ setTimeout({ var oHead=document.getElementsByTagName('head'); var oCss=document.createElement("link"); oCss.rel="stylesheet"; oCss.href="./preimgcss.css"; var oJs=document.createElement("script"); oJs.src="./preimgjs.js"; oHead.appendChild(oCss); oHead.appendChild(oJs); new Image().src="http://ubmcmm.baidustatic.com/media/v1/0f000KLR1mFt_P41d9V_j0.jpg" },1000) },1000)

    preimgcss.css只是设定img的样式就不上传了

    为什么在html文件中使用ajax加载js和css,js和css的加载不会影响当前预加载页面。

总结

  本质上后两种方法都是一样的,都是先建立一个Image对象,给img对象依次赋地址, 达到预加载的情况

  

转载于:https://www.cnblogs.com/dirkhe/p/6874184.html

相关资源:图片预加载loading

最新回复(0)