如何加快加载数千张图片的速度?

How can I speed up loading thousands of images?

我正在使用 d3 设置数千个填充了不同图像的矩形。这是 'def' 部分的代码。

` d3.json("data/data.json", 函数(错误, 数据){

    var rects = svg.selectAll("rect")
                .data(data);                    
    rects.enter()
        .append("rect")
        .attr("x", 0)
        .attr("y", function(d,i) {
            return i*barheight ;
        })
        .attr("class", "bar")
        .attr("width", barwidth)
        .attr("height", barheight)
        .attr("fill", function(d){
            return "rgb"+ d.rgb;
        });

//更改封面图片

    var def = defsvg.selectAll("def")
                .data(data);

     def.enter()
        .append("pattern")
        .attr("id", function(d){
            return d.name
        })
        .attr("width", 1)
        .attr("height", 1)
        .append("image")
        .attr("width", coverwidth)
        .attr("height", coverheight)
        .attr("xlink:href", function(d){
            return "img/" + d.name;
        });


    cover.attr("x", 0)
        .attr("y", 0)
        .attr("width", coverwidth)
        .attr("height", coverheight)
        .append("rect")
        .attr("width", coverwidth)
        .attr("height", coverheight);

    d3.selectAll("rect")
        .on("click", function(d){
            cover.attr("fill", function(){
                return "url(#" + d.name + ")";
            });
        });
    })

`

但问题是数据是14000+。对应的,文件夹"img"中有14000+项。尽管每张图片只有 30kb,但对于该项目来说仍然足够,尤其是在移动设备上启动时。有什么解决办法吗?谢谢!

这完全未经测试,但会在 click 事件中加载图像。这里 defs 是 SVG 中 <defs> 节点的 d3 选择。您不需要数据绑定并预先创建所有 pattern 节点。这应该创建图案,向其附加图像,等待图像加载,然后最后填充矩形。

d3.selectAll("rect")
  .on("click", function(d) {
    defs.append("pattern")
      .attr("id", d.name)
      .attr("width", 1)
      .attr("height", 1)
      .append("image")
      .attr("onload", function() {
        cover.attr("fill", "url(#" + d.name + ")");
      })
      .attr("width", coverwidth)
      .attr("height", coverheight)
      .attr("xlink:href", "img/" + d.name);
    });