控制 HTML 中的图像加载顺序 [英] Controlling image load order in 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?
谢谢
推荐答案
使用 Javascript,稍后填充图像 src
属性.#
告诉浏览器链接到页面上的 URL,因此不会向服务器发送请求.(如果 src
属性为空,则仍会向服务器发出请求 - 不太好.)
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 the src
property was empty, a request is still made to the server - not great.)
组合图像地址数组,并通过它递归,加载图像并在每个图像的 onload
或 onerror
方法返回值时调用递归函数.
Assemble an array of image addresses, and recurse through it, loading your images and calling a recursive function when the onload
or onerror
method for each image returns a value.
HTML:
<img src='#' id='img0' alt='[]' />
<img src='#' id='img1' alt='[]' />
<img src='#' id='img2' alt='[]' />
JS:
var imgAddresses = ['img1.png','img2.jpg','img3.gif'];
function loadImage(counter) {
// Break out if no more images
if (counter==imgAddresses.length) { return; }
// Grab an image obj
var I = document.getElementById("img"+counter);
// Monitor load or error events, moving on to next image in either case
I.onload = I.onerror = function() { loadImage(counter+1); }
//Change source (then wait for event)
I.src = imgAddresses[counter];
}
loadImage(0);
您甚至可以使用 document.getElementsByTagName("IMG")
.
顺便说一下,如果您需要加载图片,这是一个不错的起点.
By the way, if you need a loading image, this is a good place to start.
编辑
为了避免对服务器的多个请求,您可以使用几乎相同的方法,只是在您准备好加载它们之前不要插入图像元素.有一个 容器等待每个图像.然后,循环遍历,获取span对象,动态插入图片标签:
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:
var img = document.createElement("IMG");
document.getElementById('mySpan').appendChild(img);
img.src = ...
然后在创建元素时只发出一次图像请求.
Then the image request is made only once, when the element is created.
这篇关于控制 HTML 中的图像加载顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!