简体   繁体   中英

Disable loading images while the web-page is loading

Most of my website visitors are using limited bandwidth & slow internet. so I'm trying to reduce the load time and save their bandwidth by disable loading images & background images while the web-page is loading, then give an option to load the web-page's images when click "show images" button.

i'm thinking of some thing like lazy load but with on-click action.

I appreciate your suggestions.

One idea:

-Keep empty src attributes for images

-Store img urls on an attribute (you can call it data-src)

-Use Jquery to replace src with data-src value when page is loaded or when User clicks "show images"

I think there are 2 different scenarios:

IMG-TAGS

HTML:

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

jQuery:

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

BACKGROUND-IMAGES

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 background-images are not loaded when a class isn't used (Same on hover etc.) It's not the most efficient way to do this, but it could give you an idea on how its done. Maybe you could store css-classes with the right background images also in data-attributes and loop through.

FIDDLE

The nested functions look a bit yucky, but here's a jQuery solution to your problem, using the method mentioned above.

 $(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM