Front-end Project Analysis: How do I picture optimization (pre-loaded and lazily)

As we all know: the picture on the front page is the most important optimization is the most troublesome part, I also want to spend a few months time to optimize to my satisfaction degree half ,,, Well, long story ah!

Optimize your images in two ways: pre-loaded and lazy loading

Let us talk about preloading : I've written a blog on a pre-loaded, but it ,,, there is not a lot of content makes me very happy, because the latter found some content in order to show action in a given situation.
Preloaded common scenarios: In the development process, we often encounter such a request, when the mouse hover up, change the background menu. If no picture pre-loaded, it will flicker. Then have a 1px eyes of designers will not let you. Why is there this situation? Because hover time, the picture will go to load.
This time, we need to use preloaded (before hover finished loading (but will increase the page load time)), and
such as the following:

<script type="text/javascript">
            <!--//--><![CDATA[//><!--
            if (document.images) {
                img1 = new Image();
                img2 = new Image();
                img3 = new Image();
                img4 = new Image();
                img1.src = "img/QQ图片20190521233736.jpg";
                img2.src = "img/Cache_3fa28786e3750c51..jpg";
                img3.src = "img/牌.png";
                img4.src = "img/Cache_46072b3594a9a6b5..jpg";
            }
            //--><!]]>
        </script>

and this:

var imgSrcArr=[
   '要预加载的图片路径'(可以多个啊)
];
var imgWrap=[];
function preloadImg(arr) {
    for(var i=0;i<arr.length;i++){
        imgWrap[i]=new Image();
        imgWrap[i].src=arr[i];
    }
}
preloadImg(imgSrcArr);

$(function () {
    preloadImg(imgSrcArr);
})

Also the classic pre-loaded, and the bottom three lines that means: wait until the text has been loaded or reloaded picture.
I'm an old blood erupted, so if I ask you why? ? ?

ajax way to achieve pre-loaded (see online, is not recommended in this way):

    $(function(){
        $.get('图片的路径');
    })
    /*
    当然我们也可以写成一个函数,这里我就不演示了
    */

We test a lot of scenes, find as I said above, in fact, is more suitable for pre-loading after such conversion hover image loading (splash screen to solve the problem), in fact, really not as good as lazy loading effect at that picture of environmental requirements page just opened. So, we can put it need to respond to mouse events (it plainly, is to see just do not need to go up) place.

But my main requirement is to load the first screen image optimization, improve the user experience, how to do it?
Preloading like ,,, I can not help
think twice, I decided to "take refuge" lazy loading force!

What is "lazy loading"?
In the picture due to some reason it does not show up, with a placeholder to show that this is a good way to improve the user experience, at present, Jingdong Mall and other sites on the use of this technology.
Lazy loading of the essence: Do not the real picture on the src introduced "placeholder map" src in place!

Why use lazy loading:
In a page, assuming that there are 20 pictures, each to 100kb, when the user does not see the point of the scroll bar only four, if these 20 pictures are set up real src, then when when the page is first loaded the browser will immediately request that 20 pictures resources, traffic 2000kb needs;
but we do lazy load only request the user to see four pictures, the browser requests only four pictures resources required flow only 400kb. This means the first screen time can be greatly reduced.

Code shows:

index.html

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <style>
            body{
                text-align: center;
            }
            .game-detail-logo{
                width: 750px;
                height: 430px;
                text-align: center;
                margin-top:30px;
            }
        </style>
        <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4259389730,3152819071&fm=26&gp=0.jpg" class="game-detail-logo lazyLoadImg" picAddress="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=4003935283,4035293154&fm=27&gp=0.jpg">
        <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4259389730,3152819071&fm=26&gp=0.jpg" class="game-detail-logo lazyLoadImg" picAddress="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1535003204948&di=7f297fc3bd01dcbca58f47c470ae9b9e&imgtype=0&src=http%3A%2F%2Fpic50.nipic.com%2Ffile%2F20141019%2F19104397_104929568000_2.jpg">
        <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4259389730,3152819071&fm=26&gp=0.jpg" class="game-detail-logo lazyLoadImg" picAddress="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2390937513,1169699994&fm=27&gp=0.jpg">
        <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4259389730,3152819071&fm=26&gp=0.jpg" class="game-detail-logo lazyLoadImg" picAddress="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6169699994&fm=27&gp=0.jpg">
        <img src="https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4259389730,3152819071&fm=26&gp=0.jpg" class="game-detail-logo lazyLoadImg" picAddress="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3947968217,2342505746&fm=27&gp=0.jpg">
    </body>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>   /*用http方式引入jQuery文件(min指压缩过的)*/
    <script type="text/javascript" src="lazyLoadImg.js"></script>
</html>

As above, in a few pictures, we will be true picture on picAddress in, put in the src footprint diagram
in js, the page load is complete, according to scrollTop determine whether the image within the user's field of vision, if so, will picAddress attribute value is stored out to the src attribute (in the event of repeated scrolling determine whether the image into view, if entered, value will be taken picAddress properties stored in the src attribute).
lazyLoadImg.js

/* 
* @example
* <img src="" class="lazyLoadImg" picAddress="">
* @param src里面写的是占位图或者说兜底图地址(一张默认填充图)
* @param class="lazyLoadImg" 是必须的标识
* @param picAddress里面写的是真正需要懒加载的图片地址
*/
const lazyLoadImg = {
  initConfig() {
    const self = this;
    self.imgObject.srcFlag = 'picAddress'; // 图片地址
    self.imgObject.class = 'lazyLoadImg'; // 惰性加载的图片需要添加的class
    self.imgObject.sensitivity = 40; // 鼠标滚动敏感度,该值越小,惰性越强(加载越少)
    self.imgObject.init();
  },
  imgObject: {
    trigger() {
      const self = this;
      const eventType = (self.isPhone && 'touchend') || 'scroll';
      self.imgListData = $('img.' + self.class + '');
      $(window).trigger(eventType);
    },
    init() {
      var self = this;
      $(window).on('scroll', function() {
        self.isLoadImg();
      });
      self.trigger();
    },
    isLoadImg() {
      const self = this;
      function loadNeedImg(img) { // 判断哪些img元素需要加载
        const windowPageYOffset = window.pageYOffset; // 滚动条距离窗口顶部的偏移量
        const offsetAddInner = window.pageYOffset + window.innerHeight; // window.innerHeight返回窗口的文档显示区的高度
        const imgOffsetTop = img.offset().top; // 当前img元素距离窗口顶部的偏移量
        return (
          imgOffsetTop >= windowPageYOffset && // 确保img元素在窗口内
          imgOffsetTop - self.sensitivity <= offsetAddInner //当前img元素是不是在窗口可见范围内,不可见返回:false
        );
      }
      function loadImg(img, index) {
        const imgUrl = img.attr(self.srcFlag);
        const imgLazy = img.attr('src');
        img.attr('src', imgUrl);
        img[0].onload ||  // 开始向服务器请求加载图片
          ((img[0].onload = function() {
            $(this)
              .removeClass(self.class)
              .removeAttr(self.srcFlag),
            (self.imgListData[index] = null),
            (this.onerror = this.onload = null);
          }),
            (img[0].onerror = function() {
              (this.src = imgLazy),
              $(this)
                .removeClass(self.class)
                .removeAttr(self.srcFlag),
              (self.imgListData[index] = null),
              (this.onerror = this.onload = null);
            }));
      }
      self.imgListData.each(function(index, val) {
        if (!val) return;
        const img = $(val);
        if (!loadNeedImg(img)) return;
        const aa = img.attr(self.srcFlag);
        if (!img.attr(self.srcFlag)) return;// 判断是否有规定的picAddress属性,没有则退出当次循环
        loadImg(img, index);
      });
    },
  },
};
lazyLoadImg.initConfig();

(Explain here, there are many online .lazyload package jQuery, but the feeling of personal use and compatibility effects are huge difference, and therefore advocate a package own js)

Here brief mention jQuery code through the package (package jQuery introduced first, very simple):

    <img src="imag/2.png" width="1920" height="340" alt="林允儿">
<!--有时为什么会有水平之间的空隙?回车符-->
<script>
    $('img').lazyload({
        //以“背景”的形式突出占位图
        placeholder:'imag/loading.gif',
        //视图滚动到这里时再加载原图
        effect:'fadeIn',
        //开始加载位置
        threshold:-170
    });
</script>

We can speed the online network set to mid-tier mobile or low-end mobile more easily see the effect! as follows:
Here Insert Picture Description

Analysis of application scenarios, choose the right way to build a more perfect website.
Project Address: Nanyang Polytechnic - excellent C community

Guess you like

Origin blog.csdn.net/qq_43624878/article/details/95226831