Javascript图像预加载策略
像许多人一样,我长期以来一直在进行图像预加载,但并不总是非常理性。因此,我想出了这个关于使用 javascript 预加载图像的正确方法的简短想法列表。
- 应尽快执行图像预加载脚本。它应该放置在 HTML 的顶部(在 HEAD 部分),与其他位于 BODY 部分底部的脚本不同。
- 它不能依赖于库(例如 jQuery),因为这会延迟执行。
- CSS 精灵和背景图像不需要预加载,因为 CSS(通常在 HTML 顶部调用)已经完成了这项工作(这当然减少了 javascript 图像预加载的总体需求)。
- 预加载脚本可以在站点的每个页面上放置并运行,以确保无论用户进入站点的哪个页面都有效。 (但是,如果只是为了检查图像现在是否已缓存,那么每次运行脚本的开销又如何呢?)
我很想听听您对这个主题的看法。
Like many people I've been doing image preload for a long time, but not always very rationally. So I've come up with this short list of thoughts about the right way to preload images with javascript.
- An image preload script should be executed as soon as possible. It should be placed at the top of the HTML (in the HEAD section), unlike the others scripts that go to the bottom of the BODY section.
- It must not rely on a library (such as jQuery) because that would delay the execution.
- CSS sprites and background-images need not be preloaded because the CSS - normally called at the top of the HTML - already does the job (this of course reduces the overall need for javascript image preload).
- The preload script can be placed and run on every page of the site so as to be sure it is effective no matter which page the user enters the site. (But what about the overhead of running the script every time, if only to check the images are now cached?)
I'd be very interested to hear your opinions on this subject.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这会优先考虑用户执行某些操作时可能显示的图像,然后优先考虑作为初始页面一部分的图像。 (除非您尝试预加载属于初始页面一部分的图像,否则这是多余的)。
这样的延迟应该不会很严重
如果样式表中提到的图像未显示,浏览器可能会优化并且不会加载它们。
合理的缓存控制标头应该避免需要发出 HTTP 请求来检查图像的新鲜度,因此这应该可以忽略不计。
This puts greater precedence on images that might be shown if the user does something then on images which are part of the initial page. (Unless you are trying to preload images which are part of the initial page, which would be redundant).
Such a delay shouldn't be significant
Browsers may optimize and not load images mentioned in stylesheets if they aren't being displayed.
Sensible cache control headers should avoid the need to make HTTP requests to check the freshness of images, so this should be negligible.