如何在内存中存储图像并从内存缓存中加载它们? [英] javascript - How to store images on memory and load them from memory insteaId of cache?
本文介绍了如何在内存中存储图像并从内存缓存中加载它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我现在正在使用以下函数将图像预加载到缓存。我想知道是否可以从内存中加载它们以获得更快的加载时间。
函数preloadImage(done,i){
if(!i){i = 1; }
var img = new Image();
img.onloadend = function(){
if(this.height == 0){return done(); }
preloadImage(done,i + 1);
};
img.src =images /+ i;
preloadImage(function(){console.log('images loaded');});
我想要加载一个 image()
元素与JavaScript,然后在幻灯片放映中显示它们。 $ c $>图像对象直接进入DOM,而不必在预取后用 src
重新加载:
< pre class =snippet-code-js lang-js prettyprint-override>
// wait 2 secondssetTimeout(()=> {//预加载图片var image = new Image(); image.addEventListener ('load',function(){//放入DOM // assert(this === image); document.querySelector('img')。replaceWith(this);}); image.src ='https:/ /www.w3schools.com/w3css/img_lights.jpg';},2000);
< img src =https://www.w3schools.com/howto/img_fjo rds.jpg/>
What I'm doing right now is using the following function to preload images to cache. I was wondering if it is possible to load them from memory for even faster load time.
function preloadImage (done, i) {
if (!i) { i = 1; }
var img = new Image();
img.onloadend = function () {
if (this.height == 0) { return done(); }
preloadImage(done, i + 1);
};
img.src = "images/" + i;
}
preloadImage(function () { console.log('images loaded'); });
What I want to do is to load an array of image()
elements with javascript and then show them in a slideshow.
解决方案
Here's how to put an Image
object directly into the DOM without having to reload with src
after prefetching:
// wait 2 seconds
setTimeout(() => {
// preload image
var image = new Image();
image.addEventListener('load', function () {
// place into DOM
// assert(this === image);
document.querySelector('img').replaceWith(this);
});
image.src = 'https://www.w3schools.com/w3css/img_lights.jpg';
}, 2000);
<img src="https://www.w3schools.com/howto/img_fjords.jpg"/>
这篇关于如何在内存中存储图像并从内存缓存中加载它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文