I am not sure if this is possible, but I want to store an image in a JavaScript variable or an object and when the page loads, I want to make those images appear where desired.
I want to know if some images are converted to binary form. Can they be converted back to images with JavaScript?
You can simply use
to create a DOM image.
A DOM image is an object in memory that contains the image binary form, so there's no need to convert it back to an image since it's already one.
It appears that the OP is requesting how to do data islands in JavaScript, specifically for images. None of the answers previously given provide such a method, so here you go.
Basically, you encode the image as a base64 string and then set that as the source of a DOM element. Setting the source of an
Image
object to a url is not equivalent, since it requires an addition HTTP connection.The above code and a full example can be found here: http://www.kawa.net/works/js/data-scheme/base64-e.html
See, this is a simple matter. But the method to approach this problem is not the way you are trying right now.
What you think will work:
We'll store the image (its binary data) in a js variable, and then slap it on the page any time.
How it will work much more easily:
you just have to create a DOM image on the page, and set its source. The browser will fetch the image from the server automatically.
Examples:
ex-1:
ex-2: (using jquery) - this is essentially the same as above, only much easier to write:
Now, there's one more thing: the browser starts fetching the image after this code runs, so the image actually appears a little after you insert it into the DOM.
To prevent this, you can pre-fetch the images using:
Cheers!