【问题标题】:javascript - How to store images on memory and load them from memory insteaId of cache?javascript - 如何将图像存储在内存中并从缓存的内存中加载它们?
【发布时间】:2018-07-18 23:26:33
【问题描述】:

我现在正在做的是使用以下函数将图像预加载到缓存中。我想知道是否可以从内存中加载它们以获得更快的加载时间。

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

我想要做的是用 javascript 加载一个 image() 元素数组,然后在幻灯片中显示它们。

【问题讨论】:

  • 你可以尝试使用localStorage。在该示例中,localStorage 用于将图像传递到下一页:您可以尝试根据需要使用它:stackoverflow.com/questions/19183180/…
  • 我想使用内存而不是磁盘。
  • 感谢您提出另一个问题,祝您的图像动画项目好运。

标签: javascript html performance caching memory


【解决方案1】:

以下是如何将 Image 对象直接放入 DOM,而无需在预取后重新加载 src

// 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"/>

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 2016-05-16
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多