控制 HTML 中的图像加载顺序
有没有办法控制网页上图像的加载顺序?我正在考虑尝试通过首先加载轻量级“加载”图形来模拟预加载器。有什么想法吗?
谢谢
Is there a way to control the load order of images on a web page? I was thinking of trying to simulate a preloader by first loading a light-weight 'LOADING' graphic. Any ideas?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Javascript,稍后填充图像
src
属性。#
告诉浏览器链接到页面上的 URL,因此不会向服务器发送请求。 (如果 src 属性为空,仍然会向服务器发出请求 - 这不太好。)组装图像地址数组,并递归遍历它,加载图像并在以下情况下调用递归函数:每个图像的
onload
或onerror
方法都会返回一个值。HTML:
JS:
您甚至可以使用
document.getElementsByTagName("IMG")
。顺便说一句,如果您需要加载图像,这是一个很好的起点。
编辑
为了避免向服务器发出多个请求,您可以使用几乎相同的方法,只是在准备好加载图像元素之前不要插入它们。有一个
容器等待每个图像。然后,循环遍历,获取span对象,并动态插入图像标签:
然后在创建元素时仅发出一次图像请求。
Use Javascript, and populate the image
src
properties later. The#
tells the browser to link to a URL on the page, so no request will be sent to the server. (If thesrc
property was empty, a request is still made to the server - not great.)Assemble an array of image addresses, and recurse through it, loading your images and calling a recursive function when the
onload
oronerror
method for each image returns a value.HTML:
JS:
You could even play around with a
document.getElementsByTagName("IMG")
.By the way, if you need a loading image, this is a good place to start.
EDIT
To avoid multiple requests to the server, you could use almost the same method, only don't insert image elements until you're ready to load them. Have a
<span>
container waiting for each image. Then, loop through, get the span object, and dynamically insert the image tag:Then the image request is made only once, when the element is created.
我认为这篇文章 https://varvy.com/pagespeed/defer-images.html给出了一个非常好的和简单的解决方案。请注意解释如何创建“空” 的部分。标签:
避免
要显示加载图像,只需将其放入 HTML 中,然后在适当的时刻/事件进行更改即可。
I think this article https://varvy.com/pagespeed/defer-images.html gives a very good and simple solution. Notice the part which explains how to create "empty" <img> tags with:
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="your-image-here">
to avoid <img src="">
To display a loading image, just put it in the HTML and change it later at the appropriate moment/event.
只需在任何其他图像之前包含“正在加载”图像即可。通常它们包含在页面的最顶部,然后当页面加载完成时,它们被 JS 隐藏。
Just include the 'loading' image before any other images. usually they are included at the very top of the page and then when the page loading completes, they are hidden by a JS.
这里有一个小的 jQuery 插件可以为您完成此操作: https://github.com/AlexandreKilian/imageorder
Here's a small jQuery plugin that does this for you: https://github.com/AlexandreKilian/imageorder