Preload方法

搜到一个Image Preload的方案,简单粗暴

1
2
const img = new Image();
img.src = url;

执行以上代码,这个url的图片就会被预加载,想要使用的时候,img.onload 即可,甚至重新new一个Image对象,赋值相同的url,都是可以复用的。

Canvas跨域报错

但是直接用会在canvas里会有个坑。

Canvas报错

当我使用canvas的 ctx.getImageData 会得到这个报错,直译过来就是有跨域数据污染了canvas。

增加一个 img.crossOrigin = “”; 即可。虽然这里设置的是空字符串,实际上起作用的属性值是anonymous。

crossOrigin可以有下面两个值:

关键字 含义
anonymous 元素的跨域资源请求不需要凭证标志设置。
use-credentials 元素的跨域资源请求需要凭证标志设置,意味着该请求需要提供凭证。

实际上,只要crossOrigin的属性值不是use-credentials,全部都会解析为anonymous,包括空字符串,包括类似’abc’这样的字符。

https://www.zhangxinxu.com/wordpress/2018/02/crossorigin-canvas-getimagedata-cors/

这样操作后就可以快乐的预加载图片,并且和Canvas愉快的玩耍了。

图片好像加载了两次

有一些图片,我不仅仅在JS里用来用去,还在HTML中img标签用到了,然而我发现这图请求了两次。

重复加载

难道img标签和js中的 Image 对象不能共用这个预加载??

或者不应该用src传链接?而是img标签有什么别的属性可以接收Image对象?

Image对象不就是img HTMLElement吗???

到底是为什么呢。。。

很细小的区别就是其中一个多了个Origin字段:

请求1
请求2

我直接去查了img标签有哪些属性,https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/img

发现了一个叫crossorigin的属性。。

没错,安排上anonymous,就可以省掉多余的那次请求了。

1
<img :src="currentBgUrl" alt="背景图" crossorigin="anonymous">

优化预加载图片数组

一开始直接一个forEach,每个url搞个对象预加载一下,目的是达到了。但还可以根据场景再优化一下。

考虑到这列图片用在刮刮乐上,图片是按顺序展示的,第一张图没加载出来,第108张图根本是用不到的。

所以:

1
2
3
4
5
6
7
8
9
10
preloadImages(imageUrls, index = 0) {
if (imageUrls && imageUrls.length > index) {
const img = new Image();
img.onload = () => {
preloadImages(imageUrls, index + 1);
};
img.crossOrigin = "";
img.src = imageUrls[index];
}
}

参考 https://www.photo-mark.com/notes/image-preloading/

加载序列

盗一下别人的测试结果

The canonical preloader shaved 1.5 seconds off the total time. But that’s not the most important statistic in this case. The top line of each chart represents the download time of the next image in the gallery — the one 90% of my users will ask for next. Using the canonical preloader code with a moderately slow connection, that image is not available to our viewer until 14.27 seconds after the page loads even though it was first in line and began downloading immediately after the main page loaded. This is because it is sharing bandwidth with a bunch of other files as you can see in the chart. With the sequential download this image has the full bandwidth to itself and is ready in 1.46 seconds — almost 1000% faster. For our most common use case this is an immense improvement.

简言之,并行加载确实省一点点点点点点时间(24.01秒 VS 25.44秒),但是跟提升的用户体验比起来显得微不足道。

我自己也测试了一下效果,理论上来说,让前面的图片先加载显然更加有意义。当然,在图片较小网速较快的情况下,这两种体验的差距几乎忽略不计。总而言之,串行加载不亏。

串行加载

并行加载

用户点击切换图片的时候,好像还是又请求了?

不得不说,加载完成后,等待用户交互,等到用户点击切换其他图片时,又发了一个请求,明明已经preload了。

我只好将所有图片preload时push到一个cache数组挂在vue实例data中,果然OK了。完美实现。

我估计是preload完img又被GC了…

https://stackoverflow.com/questions/15736501/non-attached-image-onload-garbage-collection

https://stackoverflow.com/a/20847365