控制HTML中的图像加载顺序 [英] Controlling image load order in HTML

查看:124
本文介绍了控制HTML中的图像加载顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来控制网页上图像的加载顺序?我想通过首先加载一个轻量级的LOADING图形来模拟预加载器。任何想法?



感谢

解决方案

使用javascript, image src 属性为空。



组装图像地址数组,并递归遍历它,加载图像并调用当每个图像的 onload onerror 方法返回一个值时,递归函数。



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']; 

函数loadImage(counter){
//如果没有更多图像,则分解
if(counter == imgAddresses.length){return; }

//获取图像obj
var I = document.getElementById(img+ counter);

//监视载入或错误事件,在任何一种情况下移动到下一个图像
I.onload = I.onerror = function(){loadImage(counter + 1); }

//改变源代码(然后等待事件)
I.src = imgAddresses [counter];
}

loadImage(0);

您甚至可以使用 document.getElementsByTagName(IMG) 。



顺便说一句,如果你需要一个加载图片,这是一个开始的好地方。



编辑



为避免向服务器发出多个请求,您可以使用几乎相同的方法,只有在准备好加载它们之前,才能插入图像元素。让一个< span> 容器等待每张图片。然后,循环,获取span对象,并动态插入图片标签:

  var img = document.createElement(IMG ); 
document.getElementById('mySpan')。appendChild(img);
img.src = ...

然后,图像请求只进行一次,该元素已创建。


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

解决方案

Use javascript, and leave your image src properties empty.

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);

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:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆