如何使图像同步加载? [英] How do I make an image load synchronously?

查看:112
本文介绍了如何使图像同步加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有图像属性的对象,但是我希望只有在加载图像后才能使contstructor完成运行。或者用代码来描述:

  GraphicObject = Class.extend({

//这是构造函数
init:function(){
this.graphic = new Image();
this.graphic.src ='path / to / file.png';

while(true)
{
this.graphic.onload = function(){break;};
//我知道这是行不通的,因为'break'是打开的一个不同的上下文
//但你得到了我想要做的。
}
}


})

对于那些不熟悉我在脚本中使用的Class符号的人,它基于



有什么想法?

Base64 和 Data-URL 古代艺术是可能的。

将GIF图片转换为BASE64。



rune.b64



  R0lGODlhIwAjAIAAAP /// wAAACwAAAAAIwAjAAACf4SPqcsb3R40ocpJK7YaA35FnPdZGxg647kyqId2SQzHqdlCdgdmqcvbHXKi4AthYiGPvp9KVuoNocWLMOpUtHaS5CS54mZntiWNRWymn14tU7c2t6ukOJlKR5OiNTzQ7wb41LdnJ1coeNg3pojGqFZniPU4lTi0d4mpucmpUAAAOw = = 

通过阻止AJAX将转换后的图像加载到同一服务器的JavaScript。



loader.js



  var request = new XMLHttpRequest(); 
var image = document.createElement('img');

request.open('GET','rune.b64',false);
request.send(null);

if(request.status === 200){
image.src ='data:image / gif; base64,'+ request.responseText.trim();

document.getElementsByTagName(body)[0] .appendChild(image);
}



问题




  • 一些旧浏览器不喜欢(大)数据网址

  • Base64编码使图像大约增加37%

  • 整个用户界面被阻止,直到图片被加载



这是非常邪恶的方式


I want to create an object that has an image property, but I want the contstructor to finish running only once the image is loaded. Or to describe this with code:

GraphicObject = Class.extend({

    //This is the constructor
    init: function(){
          this.graphic = new Image();
          this.graphic.src = 'path/to/file.png';

          while(true)
          {
              this.graphic.onload = function(){break;};
              //I know this won't work since the 'break' is on a different context
              //but you got what I try to do.
          }
     }


})

For those who are unfamiliar with the Class notation I'm using in my script, it's based on this

Any ideas?

解决方案

It is possible, but only with the ancient art of Base64 and Data-URL.

GIF image converted to Base64.

rune.b64

R0lGODlhIwAjAIAAAP///wAAACwAAAAAIwAjAAACf4SPqcsb3R40ocpJK7YaA35FnPdZGxg647kyqId2SQzHqdlCdgdmqcvbHXKi4AthYiGPvp9KVuoNocWLMOpUtHaS5CS54mZntiWNRWymn14tU7c2t6ukOJlKR5OiNTzQ7wb41LdnJ1coeNg3pojGqFZniPU4lTi0d4mpucmpUAAAOw==

JavaScript which loads the converted image form the same server via blocking AJAX.

loader.js

var request = new XMLHttpRequest();
var image = document.createElement('img');

request.open('GET', 'rune.b64', false);
request.send(null);

if (request.status === 200) {
  image.src= 'data:image/gif;base64,' + request.responseText.trim();

  document.getElementsByTagName("body")[0].appendChild(image); 
}

Problems

  • Some older browsers don't like (big) Data-URLs
  • Base64 encoding makes images about 37% bigger
  • The whole UI is blocked till the image is loaded

This is a very-evil way

这篇关于如何使图像同步加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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