【问题标题】:Disable loading images while the web-page is loading在网页加载时禁用加载图像
【发布时间】:2016-03-23 20:55:33
【问题描述】:

我的大多数网站访问者都使用有限的带宽和缓慢的互联网。 所以我试图通过在网页加载时禁用加载图像和背景图像来减少加载时间并节省带宽,然后在单击“显示图像”按钮时提供加载网页图像的选项。

我正在考虑一些类似延迟加载但具有点击操作的东西。

感谢您的建议。

【问题讨论】:

标签: javascript jquery lazy-loading


【解决方案1】:

一个想法:

-为图片保留空的 src 属性

-将img urls存储在一个属性上(你可以称之为data-src)

-当页面加载或用户点击“显示图片”时,使用Jquery将src替换为data-src值

【讨论】:

    【解决方案2】:

    我认为有两种不同的情况:

    IMG-标签

    HTML:

    <img src="" data-load="http://imagesource" alt="">
    

    jQuery:

    $('img[data-load]').each(function(){        
      $(this).attr('src', $(this).data('load'));
    });
    

    背景图片

    HTML:

    <div class="background-placeholder"></div>
    

    CSS:

    .background-placeholder {
      background-color:#fff;
      width:250px;
      height:250px;
    }
    
    .show-bg1 {
      background-image:url('http://imagesource');
    }
    

    jQuery:

    $('.background-placeholder').addClass('show-bg1');
    

    当不使用类时,不加载 CSS背景图像(悬停时相同) 这不是最有效的方法,但它可以让您了解它是如何完成的。 也许您可以将具有正确背景图像的 css 类也存储在数据属性中并循环。

    FIDDLE

    【讨论】:

      【解决方案3】:

      嵌套函数看起来有点恶心,但这里有一个 jQuery 解决方案,使用上面提到的方法。

      $(document).ready(function(){ // wait until the document is loaded
        $('#loadimages').click(function(){ // before registering the event handler 	
          $('img[data-src]').each(function(){ // and for each image with a data-src attribute    	
            $(this).attr('src', $(this).data('src')) // copy it's contents into the src attribute
          })
        })
      })
      img[data-src]{
        width: 200px;
        height: 400px;
        background: grey;
        position: relative;
      }
      
      img[data-src][src=""]::after {
        content: 'Placeholder';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, 50%);
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <img src="" data-src="http://lorempixel.com/200/400"/> 
      <img src="" data-src="http://lorempixel.com/200/400"/>
      <img src="" data-src="http://lorempixel.com/200/400"/>
      <button id="loadimages">Load Images</button>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多