我正在寻找一个快速和简单的方法,预加载图像与JavaScript。如果这很重要,我将使用jQuery。
我在这里看到了这个(http://nettuts.com...):)
function complexLoad(config, fileNames) {
for (var x = 0; x < fileNames.length; x++) {
$("<img>").attr({
id: fileNames[x],
src: config.imgDir + fileNames[x] + config.imgFormat,
title: "The " + fileNames[x] + " nebula"
}).appendTo("#" + config.imgContainer).css({ display: "none" });
}
};
但是,对于我想要的东西来说,这看起来有点夸张!
我知道有jQuery插件在那里做这个,但他们似乎都有点大(大小);我只需要一个快速,简单和短的方式预加载图像!
使用JavaScript图像对象。
这个函数允许你在加载所有图片时触发一个回调。但是,请注意,如果至少有一个资源没有加载,它将永远不会触发回调。这可以通过实现onerror回调和增加加载值或处理错误来轻松修复。
var preloadPictures = function(pictureUrls, callback) {
var i,
j,
loaded = 0;
for (i = 0, j = pictureUrls.length; i < j; i++) {
(function (img, src) {
img.onload = function () {
if (++loaded == pictureUrls.length && callback) {
callback();
}
};
// Use the following callback methods to debug
// in case of an unexpected behavior.
img.onerror = function () {};
img.onabort = function () {};
img.src = src;
} (new Image(), pictureUrls[i]));
}
};
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('a');
});
preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
console.log('b');
});
我通常在我的项目中使用这段代码来加载页面中的图像。
你可以在这里看到结果https://jsfiddle.net/ftor34ey/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />
<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
.bg {
background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
}
</style>
<div class="bg"></div>
<div id="loadingProgress"></div>
脚本将页面的所有src和background-image保存在一个数组中并加载它们。
你可以通过var loadCount查看/读取/显示加载的进度。
let backgroundImageArray = [];
function backgroundLoading(i) {
let loadCount = 0;
let img = new Image();
$(img).on('load', function () {
if (i < backgroundImageArray.length) {
loadCount = parseInt(((100 / backgroundImageArray.length) * i));
backgroundLoading(i + 1);
} else {
loadCount = 100;
// do something when the page finished to load all the images
console.log('loading completed!!!');
$('#loadingProgress').append('<div>loading completed!!!</div>');
}
console.log(loadCount + '%');
$('#loadingProgress').append('<div>' + loadCount + '%</div>');
}).attr('src', backgroundImageArray[i - 1]);
}
$(document).ready(function () {
$('*').each(function () {
var backgroundImage = $(this).css('background-image');
var putInArray = false;
var check = backgroundImage.substr(0, 3);
if (check == 'url') {
backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
backgroundImage = backgroundImage.replace('"', '');
backgroundImage = backgroundImage.replace('"', '');
if (backgroundImage.substr(0, 4) == 'http') {
backgroundImage = backgroundImage;
}
putInArray = true;
} else if ($(this).get(0).tagName == 'IMG') {
backgroundImage = $(this).attr('src');
putInArray = true;
}
if (putInArray) {
backgroundImageArray[backgroundImageArray.length] = backgroundImage;
}
});
backgroundLoading(1);
});
$.fn.preload = function (callback) {
var length = this.length;
var iterator = 0;
return this.each(function () {
var self = this;
var tmp = new Image();
if (callback) tmp.onload = function () {
callback.call(self, 100 * ++iterator / length, iterator === length);
};
tmp.src = this.src;
});
};
用法很简单:
$('img').preload(function(perc, done) {
console.log(this, perc, done);
});
http://jsfiddle.net/yckart/ACbTK/