Reputation: 313
Is there a way to load an image specified in the src attribute of image tag in an html asynchronously?
My ultimate aim is to hit a java class through a image src tag. I want that to be asynchronously without disturbing current functionality of the web page.
How can this be done?
Upvotes: 1
Views: 4347
Reputation: 707198
All images are loaded asychronously. If the <img>
tag with src
attribute specified is present in the initial HTML of the page, it will start loading immediately as the page's HTML is parsed and loaded.
If you want to control when it starts to load, then you cannot specify the img URL in the HTML of the page.
For example, this javascript will load an img asychronously when you call this function and it will call your callback when it's successfully loaded:
function createImg(url, fn) {
var img = new Image();
img.onload = fn;
img.src = url;
return(img);
}
You can then put this image tag in your page by adding it to the page DOM if you want.
Based on your comments, it's not clear what you're really trying to do. Perhaps you really just want to issue an ajax call to your server and don't need to mess with img tags at all.
Upvotes: 2
Reputation: 108480
Any IMG
tag with a src attribute will load immediately when the page is requested.
You can put the source in a data attribute instead if you want to control how and when the image should be requested.
Upvotes: 1