Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an image load synchronously?

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?

like image 292
Loupax Avatar asked Feb 23 '12 20:02

Loupax


People also ask

How do you load synchronous images?

To make an image load synchronously with JavaScript, we can make a promise that loads the image. We define the loadImage functino that returns a promise with the img element. We create the img element with the Image constructor. And we call resolve with img once the image has been loaded by setting the img.

How do you load asynchronous images?

For async loading to work, either load it in JavaScript and use the onload, or include the image tag on the page, without the src attribute (specify the width and height in HTML), and go back at some point, in JS, and set the image URL.

What is image onload?

The . onload event is mainly used within the element body to execute a script once a web page has loaded all contents, including images, script, CSS files, etc. The browsers used will allow us to track the loading of external resources such as images, scripts, iframes, etc.

What loaded image?

A load image is an object file which contains the load addresses and initialized sections of one or more executable files.


1 Answers

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

like image 159
K.. Avatar answered Nov 02 '22 19:11

K..