Downloading an image into Javascript and inserting it into HTML after completion

Downloading an image into Javascript and inserting it into HTML after completion

Download and store an image into Javascript before displaying it in your HTML document once the image is loaded


With Javascript, it is possible to load an image from the server using an Image object. This can be useful for pre-loading images onto the client computer before displaying it in the HTML document, while the image loads you can display a loading text or animation to let the user know there is progress being made.


Step-by-step procedure:

-Create a new Image object and assign it to a variable


-Set the Image object's "src" property to the URL of the image (which request the image from that URL and begin loading it)


-Assign a function to the Image object's "onload" event


-Within the function, add a new image element to your HTML document using the same URL for the "src" attribute


When the image has successfully downloaded onto the client machine and stored within the image object, the "onload" function will be called and an image element will be added to the HTML document with the same src value as previously used, the image will be added instantly due to the file being already loaded onto the client computer.


If you are loading an image that resides within your website directory, then you do not have to include the full URL, simply state the relative path to the image file from the web page's directory.


Example:

HTML:


<div id="img_container">    
 Loading image     
</div>     

Javascript:


var imgContainer = document.getElementById("img_container");     
var testImg = new Image;     
testImg.src = "images/test.png";     
     
testImg.onload = function(){     
 imgContainer.innerHTML="<img src='images/test.png'>";     
};     


The above example will display the text "Loading image" until the image file has been loading into the image object, then it will add a new image element into the container with the URL that we have loaded.



Christopher Thornton@Instructobit 6 years ago
or