【问题标题】:Preloading SVG images预加载 SVG 图像
【发布时间】:2015-08-12 17:33:43
【问题描述】:

我有大约一百个简单的 SVG 图像,它们存储在大约五个不同的图像文件夹中。目前,当需要显示它们时,它们会立即被检索。这在大多数情况下是有效的,但它有时会导致闪烁,我想消除它。有没有办法在需要它们之前预加载这些图像,以便它们被缓存?我在这里看到了一些解决方案,但它们主要处理少量图像。有没有首选的方式来进行大容量预加载?

谢谢!

【问题讨论】:

标签: javascript php html css svg


【解决方案1】:

如果你有图片的所有 URL,你可以尽快开始使用 url 将它们缓存在 JS 对象中,然后在需要时从那里获取它们。

在您的页面中,您可能在某处存储了 SVG 图像列表,但最后您需要的只是一个 JS 数组的 URL 字符串。

这是一个简单的例子:

// assuming you've gotten the urls from somewhere and put them in a JS array
var urls = ['url_image_1.svg', 'url_image_2.svg', ... ];

var svgCache = {};

function loaded(){
  // just increment the counter if there are still images pending...
  if(counter++ >= total){
    // this function will be called when everything is loaded
    // e.g. you can set a flag to say "I've got all the images now"
    alldone();
  }
}

var counter = 0;
var total = urls.length;

// This will load the images in parallel:
// In most browsers you can have between 4 to 6 parallel requests
// IE7/8 can only do 2 requests in parallel per time
for( var i=0; i < total; i++){
  var img = new Image();
  // When done call the function "loaded"
  img.onload = loaded;
  // cache it
  svgCache[urls[i]] = img;
  img.src = urls[i];
}

function alldone(){
  // from this point on you can use the cache to serve the images
  ...
  // say you want to load only the first image
  showImage('url_image_1.svg', 'imageDivId');
}

// basically every time you want to load a different image just use this function
function showImage(url, id){
  // get the image referenced by the given url
  var cached = svgCache[url];
  // and append it to the element with the given id
  document.getElementById(id).appendChild(cached);
}

注意

  • 还要考虑加载图像时出错的情况,因此也将回调发送到 img.onerror 并提供一些“丢失”图像作为替换的情况
  • 这里还有一些需要考虑的事项,例如 SVG 的一些浏览器怪癖,但基本解决方案应该可以工作。

【讨论】:

  • 感谢非常详细的回答!一旦它们被缓存,我是否仍然可以像以前那样调用它们,它只会从缓存中提取它,还是我需要使用 svgCache 数组?对不起,我对此一无所知!
  • 我添加了一个函数来将图像附加到 DOM 以及如何在 alldone 函数中调用它。
  • 再次感谢!最后一个问题......你会建议我把这个脚本放在哪里?在头部标签中?
  • 一旦您准备好执行图像列表。如果您想保持一切清洁,或者与其他脚本一起使用。
  • 我不断收到一条错误消息,指出“未捕获的 TypeError:无法读取 null 的属性 'appendChild'”,即使我传入的 id 是我的 DOM 上的有效 id...有什么想法吗?跨度>
【解决方案2】:

这是一个 css 解决方案:

.my-class{
    // this will put the rollover image behind and act as a preloader
    background-image:url('../images/svg/btn.svg'), url('../images/svg/btn-over.svg');
}

.my-class:over{
    background-image:url('../images/svg/btn_over.svg');
}

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2016-05-02
    相关资源
    最近更新 更多