关于图片预加载的思考

引子:

很多时候,我们在写html页面的时候,当需要在页面中加入图片时,我们很自然地把图片直接用<img>标签放在了<body>里面,这本来是没有多大问题的。

但是当图片数量很多的时候,问题就来了。Html页面在被解析器解析的时候要不断去寻找图片的路径去加载图片,而这些图片不一定所以都会被用户通过触发一些类似点击的操作所看到。这样,一些不必要的图片预加载就会拉长了页面的加载时间,带来的用户体验是不好的。

为了解决这个性能问题,有一个比较好的解决问题就是用js去延迟图片预加载。那么具体的实现过程是怎样的呢?

我先把我实现的代码放在下面:

<html lang="en">
<head>
         <meta charset="UTF-8">
         <title>Document</title>
<style>
  body{position:relative;text-decoration: none;list-style: none;}

  .showpic{position:absolute;height:550px;width:90%;margin-left:80px;background-color: black;}

  .button-box{position: absolute;margin-top:560px;margin-left: 600px;z-index: 5;}

  .preload{position: fixed;height: 100%;width:100%;top:0;background-color: white;display: none;}

  img{position: absolute;margin-left: 30px;margin-top: 3px;}

  button{height: 30px;width:80px;font-size: 10px;}
</style>
<script  src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>

<body>
         <div class="showpic">
                  <img src="img/pexels-photo-297814.jpeg" id="img">
         </div>

         <div class="button-box">
                   <button type="button" value="前一张"  data-control="prev" class="button">前一张</button>
                   <button type="button" value="后一张"  data-control="next" class="button">后一张</button>
         </div>
         <div class="preload"></div>

<script type="text/javascript" src="js/preload.js"></script>
</body>
</html>


$(document).ready(function(){

         var imgs = ["img/pexels-photo-297814.jpeg",
                                     "img/pexels-photo-465445.jpeg",
                                     "img/pexels-photo-619948.jpeg",
                                     "img/pexels-photo-620336.jpeg",
                                     "img/pexels-photo-885746.jpeg",
                                     "img/pexels-photo-886109.jpeg",
                                     "img/pexels-photo-888994.jpeg"];

         var  index = 0,
         len =imgs.length;

        $(".button").on("click",function(){

                 if($(this).data('control')=== "prev"){
                           index = Math.max(0,--index);
                 }else{
                           index = Math.min(len-1,++index);
                 }

                 $("#img").attr("src",imgs[index]);

        });

});

 

这个案例我是要实现通过点击按钮实现图片的展示过程。显然,我在<div class="showpic">盒子的<img>标签里面只是放了一张图片(避免页面打开是什么也没有),并没有把全部可以展示的图片都放在盒子里面。因为这样势必会加大web浏览器解析html页面的压力。

我把这些图片的所有搜索路径的放在了js代码中,并通过修改src属性的方法来更新<img>标签,其中我还用到了html的data属性来自定义点击按钮的类型,并通过在js中获取这个data值来确定图片路径的更改。

这样的实现,就比较有利于减轻html页面解析过程中对浏览器解析器的压力。

原文地址:https://www.cnblogs.com/thomson-fred/p/9404366.html