HTML图片顺序加载

2. JavaScript 中图片顺序加载,防止页面阻塞

  • 浏览器一般只能同时存在4-8个连接(chrome6个),为了使得图片和页面渲染同时进行,需要保证图片加载只有一个连接使用,即顺序加载:

 

JavaScript 代码

复制代码
 1 $(function(){
 2     //获取页面所有图片
 3     var images = document.images;
 4     //图片异步加载
 5     preload(images,0);
 6 });
 7 
 8 //图片异步加载
 9 function preload(images, index) {
10     index = index || 0;
11     if (images && images.length > index) {
12         var img = images[index];
13         //图片加载完成后回到函数中开始加载下一张图片
14         img.onload = function() {
15             preload(images, index + 1);
16         };
17         var src = "download?id="+images[index].id+"&isThumball=false";
18         img.src = src;
19     }
20 }
复制代码

HTML 代码

 

1 <img src="" id="${drawingImg.id}" alt="${drawingImg.imageName }"></div>

 

1. 图片下载方法DEMO:

复制代码
 1 @RequestMapping("download")
 2  public void downFile(@RequestParam("id") String id, HttpServletResponse response) throws Exception {
 3     List<ImageVO> list = imageService.getImageInfoBySrctypeAndDataId(SrcTypeEnum.MATERIAL.getValue(), id);
 4     OutputStream out = new ByteArrayOutputStream();
 5     String imageId = "";
 6     String fileName = String.valueOf(new Date().getTime()) + ".jpg";
 7     if (list.size() > 0) {
 8         ImageVO image = list.get(0);
 9         imageId = image.getImageId();
10         image.getName();
11         fileName = image.getName();
12     }
13     out = imageService.downloadImage(imageId, CompressLevel.STANDARD, true);
14     response.setContentType("application/octet-stream");
15 
16     // 设置下载文件名
17     response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
18     OutputStream outstrm = response.getOutputStream();
19     outstrm.write(((ByteArrayOutputStream) out).toByteArray());
20     outstrm.flush();
21     out.close();
22     outstrm.close();
23 }
复制代码

 

posted @   沽名钓誉  阅读(2720)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示