Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

预加载图片 #85

Open
coconilu opened this issue Oct 6, 2018 · 0 comments
Open

预加载图片 #85

coconilu opened this issue Oct 6, 2018 · 0 comments

Comments

@coconilu
Copy link
Owner

coconilu commented Oct 6, 2018

实现原理

浏览器对于http get请求是有缓存功能的。

同一个网页内,如果已经加载过一张图片的话,再次请求这张图片(URL一样),浏览器将不会发起http请求,而是从缓存中取出图片并返回,status code为304。

很幸运的是,浏览器提供的web api里面有一个Image类,语句new Image()将会创建一个新的HTMLImageElement实例,等价于 document.createElement('img')。

所以我们可以通过Image实例达到缓存功能。

实现代码

核心代码如下:

function preLoadPicture(pictureURL) {
  let cachePicture = new Image()
  cachePicture.scr = pictureURL
  return cachePicture
}

为了提高用户体验,可以在document的DOMContentLoaded事件和window的load事件中预加载图片。

参考

实现图片预加载的几种方式
Image()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant