Abouasy
Abouasy

Reputation: 896

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.

Upvotes: 5

Views: 2779

Answers (3)

Chris
Chris

Reputation: 793

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

Upvotes: 2

jonny
jonny

Reputation: 3098

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>

Upvotes: 0

esedeerre
esedeerre

Reputation: 111

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"

Upvotes: 2

Related Questions