简体   繁体   English

使用JavaScript异步将图像加载到网页

[英]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? 有没有办法在html中异步加载图像标签的src属性中指定的图像?

My ultimate aim is to hit a java class through a image src tag. 我的最终目标是通过图像src标签来打一个java类。 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. 如果在页面的初始HTML中存在指定了src属性的<img>标记,则它将在分析和加载页面的HTML时立即开始加载。

If you want to control when it starts to load, then you cannot specify the img URL in the HTML of the page. 如果要控制何时开始加载,则无法在页面的HTML中指定img URL。

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: 例如,当你调用这个函数时,这个javascript会异步加载一个img,它会在成功加载时调用你的回调函数:

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. 然后,您可以根据需要将此图像标记添加到页面DOM中。

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. 也许你真的只想向你的服务器发出一个ajax调用,而根本不需要乱用img标签。

Any IMG tag with a src attribute will load immediately when the page is requested. 当请求页面时,任何具有src属性的IMG标签都会立即加载。

You can put the source in a data attribute instead if you want to control how and when the image should be requested. 如果要控制应如何以及何时请求图像,则可以将源置于data属性中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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