Skip to content

Instantly share code, notes, and snippets.

@niamrox
Created August 26, 2017 20:34
Show Gist options
  • Save niamrox/bd76b39383139451340dcd7eeac6e3f3 to your computer and use it in GitHub Desktop.
Save niamrox/bd76b39383139451340dcd7eeac6e3f3 to your computer and use it in GitHub Desktop.
initApplyImageLoad: function () {
var $container = $('.site-content');
var $status = $('#status');
var $progress = $('progress');
var supportsProgress = $progress[0] &&
// IE does not support progress
$progress[0].toString().indexOf('Unknown') === -1;
var loadedImageCount, imageCount;
$(window).load( function() {
$('.site-content img').wrap("<div class='img-wrap is-loading'></div>");
// var $item = $('.site-content img').parent();
// $item.addClass('is-loading');
// use ImagesLoaded
$container.imagesLoaded()
.progress( onProgress )
.always( onAlways );
imageCount = $container.find('img').length;
resetProgress();
updateProgress( 0 );
});
// return doc fragment with
function getItems() {
var items = '';
for ( var i = 0; i < 7; i++ ) {
items += image.img.src;
}
return items;
}
function resetProgress() {
$status.css({ opacity: 1 });
loadedImageCount = 0;
if ( supportsProgress ) {
$progress.attr( 'max', imageCount );
}
}
function updateProgress( value ) {
if ( supportsProgress ) {
$progress.attr( 'value', value );
} else {
// if you don't support progress elem
$status.text( value + ' / ' + imageCount );
}
}
// triggered after each item is loaded
function onProgress( imgLoad, image ) {
// change class if the image is loaded or broken
var $item = $( image.img ).parent();
$item.removeClass('is-loading');
if ( !image.isLoaded ) {
$item.addClass('is-broken');
}
// update progress element
loadedImageCount++;
updateProgress( loadedImageCount );
}
// hide status when done
function onAlways() {
$status.css({ opacity: 0 });
}
},
@niamrox
Copy link
Author

niamrox commented Aug 26, 2017

/loading image/

#image-container img {
max-height: 140px;
}

img,
#status {
-webkit-transition: opacity 0.4s;
-moz-transition: opacity 0.4s;
-ms-transition: opacity 0.4s;
transition: opacity 0.4s;
}

.is-loading {
background-color: black;
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/loading.gif);
width: auto;
height: auto;
position: relative;
background-repeat: no-repeat;
background-position: 50%;
}

.is-loading img {
position: relative;
}

.is-loading img:after {
content: "";
background: red;
width: 100%;
height: 100%;
}

.is-broken {
background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/82/broken.png');
background-color: #be3730;
width: 120px;
}

.is-loading img,
.is-broken img {
opacity: 0;
}

#status {
opacity: 0;
position: fixed;
right: 20px;
top: 20px;
background: hsla(0, 0%, 0%, 0.8);
padding: 20px;
border-radius: 10px;
z-index: 2; /* over other stuff */
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment