imagesLoaded jQuery

imagesLoaded jQuery插件,图片加载完毕执行内容

http://imagesloaded.desandro.com/

( function( window ) {

'use strict';

var $progress, $status;
var supportsProgress;
var loadedImageCount, imageCount;

$( function() {
var $demo = $('#demo');
var $container = $demo.find('#image-container');
$status = $demo.find('#status');
$progress = $demo.find('progress');

supportsProgress = $progress[0] &&
// IE does not support progress
$progress[0].toString().indexOf('Unknown') === -1;

$('#add').click( function() {
// add new images
var items = getItems();
console.log( items );
$container.prepend( $(items) );
// use ImagesLoaded
$container.imagesLoaded()
.progress( onProgress )
.always( onAlways );
// reset progress counter
imageCount = $container.find('img').length;
resetProgress();
updateProgress( 0 );
});

// reset container
$('#reset').click( function() {
$container.empty();
});
});

// ----- ----- //

// return doc fragment with
function getItems() {
var items = '';
for ( var i = 0; i < 7; i++ ) {
items += getImageItem();
}
return items;
}

// return an <li> with a <img> in it
function getImageItem() {
var item = '<li class="is-loading">';
item.className = 'is-loading';
var size = Math.random() * 3 + 1;
var width = Math.random() * 110 + 100;
width = Math.round( width * size );
var height = Math.round( 140 * size );
var rando = Math.ceil( Math.random() * 1000 );
// 10% chance of broken image src
// random parameter to prevent cached images
var src = rando < 100 ? '//foo/broken-' + rando + '.jpg' :
// use lorempixel for great random images
'//lorempixel.com/' + width + '/' + height + '/' + '?' + rando;
item += '<img src="' + src + '" /></li>';
return item;
}

// ----- ----- //

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 });
}

})( window );

效果演示:

http://codepen.io/kujian/full/aDeby/


关注我

我的微信公众号:前端开发博客,在后台回复以下关键字可以获取资源。

  • 回复「小抄」,领取Vue、JavaScript 和 WebComponent 小抄 PDF
  • 回复「Vue脑图」获取 Vue 相关脑图
  • 回复「思维图」获取 JavaScript 相关思维图
  • 回复「简历」获取简历制作建议
  • 回复「简历模板」获取精选的简历模板
  • 回复「加群」进入500人前端精英群
  • 回复「电子书」下载我整理的大量前端资源,含面试、Vue实战项目、CSS和JavaScript电子书等。
  • 回复「知识点」下载高清JavaScript知识点图谱

每日分享有用的前端开发知识,加我微信:caibaojian89 交流