我如何测试一个URL是否是一个有效的图像(在JavaScript中)? [英] How can I test if a URL is a valid image (in javascript)?

查看:140
本文介绍了我如何测试一个URL是否是一个有效的图像(在JavaScript中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在提交表单时,我想确保一个字段是一个有效的图像URL。

When submitting a form, I want to make sure a field is a valid image URL.

我可以在我的服务器上创建一个AJAX端点,

I could make an AJAX endpoint on my server which CURLs the URL and parses the output with an image library, but that feels a bit of overkill.

我可以避开制作一个< img> 元素然后同步检查响应?

Could I get away with making an <img> element then synchronously check the response somehow?

推荐答案

您可以使< img> 元素并处理其 onerror onload 事件。

You can make an <img> element and handle its onerror and onload events.

如果加载事件触发,这是一个有效的图像;如果错误事件触发,那不是。

这甚至可以跨域使用。

If the load event fires, it's a valid image; if the error event fires, it isn't.
This even works across domains.

这篇关于我如何测试一个URL是否是一个有效的图像(在JavaScript中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆