我想使用ng-repeat
在页面中显示超过100张图片。这些图像在加载时花费了大量时间,我不希望显示它们被加载到用户。所以,我只想在浏览器中加载它们之后显示它们。
如果所有图像都已加载,有没有办法检测?
答案 0 :(得分:11)
你可以像这样使用load
事件。
image.addEventListener('load', function() {
/* do stuff */
});
Angular Directives
单张图片解决方案
HTML
<div ng-app="myapp">
<div ng-controller="MyCtrl1">
<loaded-img src="src"></loaded-img>
<img ng-src="{{src2}}" />'
</div>
</div>
JS
var myApp = angular.module('myapp',[]);
myApp
.controller('MyCtrl1', function ($scope) {
$scope.src = "http://lorempixel.com/800/200/sports/1/";
$scope.src2 = "http://lorempixel.com/800/200/sports/2/";
})
.directive('loadedImg', function(){
return {
restrict: 'E',
scope: {
src: '='
},
replace: true,
template: '<img ng-src="{{src}}" class="none"/>',
link: function(scope, ele, attr){
ele.on('load', function(){
ele.removeClass('none');
});
}
};
});
CSS
.none{
display: none;
}
http://jsfiddle.net/jigardafda/rqkor67a/4/
如果您看到jsfiddle演示,您会注意到src
图像仅在图像完全加载后显示,而在src2
的情况下,您可以看到图像加载。(禁用缓存以查看差异)
多张图片解决方案
HTML
<div ng-app="myapp">
<div ng-controller="MyCtrl1">
<div ng-repeat="imgx in imgpaths" ng-hide="hideall">
<loaded-img isrc="imgx.path" onloadimg="imgx.callback(imgx)"></loaded-img>
</div>
</div>
</div>
JS
var myApp = angular.module('myapp',[]);
myApp
.controller('MyCtrl1', function ($scope, $q) {
var imp = 'http://lorempixel.com/800/300/sports/';
var deferred;
var dArr = [];
var imgpaths = [];
for(var i = 0; i < 10; i++){
deferred = $q.defer();
imgpaths.push({
path: imp + i,
callback: deferred.resolve
});
dArr.push(deferred.promise);
}
$scope.imgpaths = imgpaths;
$scope.hideall = true;
$q.all(dArr).then(function(){
$scope.hideall = false;
console.log('all loaded')
});
})
.directive('loadedImg', function(){
return {
restrict: 'E',
scope: {
isrc: '=',
onloadimg: '&'
},
replace: true,
template: '<img ng-src="{{isrc}}" class="none"/>',
link: function(scope, ele, attr){
ele.on('load', function(){
console.log(scope.isrc, 'loaded');
ele.removeClass('none');
scope.onloadimg();
});
}
};
});
要检测是否已加载所有图像,
对于每个图像,我生成了一个deferred
对象,并将其deferred.resolve
作为指令的图像onload回调传递,然后将deferred
个对象promise
推送到数组中。然后我使用$q.all
来检测所有这些承诺是否已经解决。
http://jsfiddle.net/jigardafda/rqkor67a/5/
更新:添加了角度方式。
更新:添加了加载多张图片的解决方案。
答案 1 :(得分:-1)
检查是否已加载所有图像
jQuery.fn.extend({
imagesLoaded: function( callback ) {
var i, c = true, t = this, l = t.length;
for ( i = 0; i < l; i++ ) {
if (this[i].tagName === "IMG") {
c = (c && this[i].complete && this[i].height !== 0);
}
}
if (c) {
if (typeof callback === "function") { callback(); }
} else {
setTimeout(function(){
jQuery(t).imagesLoaded( callback );
}, 200);
}
}
});
$('.wrap img').imagesLoaded(function(){
alert('all images loaded');
});
注意:此代码对我有用,来源:
http://wowmotty.blogspot.in/2011/12/all-images-loaded-imagesloaded.html