简体   繁体   中英

loading a image to a web page asynchronously using JavaScript

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM