开发者

How to check if an image was found on a web site?

I am using Ruby on Rails v3.0.9 and I would like to check if an image (in my case a favicon.ico icon image) is successfully retrieved from a web site and if not I would like to display a custom image.

In order to retrieve the favicon.ico image related t开发者_高级运维o a web site, in my view file I have:

image_tag "#{web_site.link}/favicon.ico", :size => "16x16"

where web_site.link values are something like the followings:

http://stackoverflow.com/
http://www.stackoverflow.com/
http://facebook.com/
...

How to check if an image was found on a web site (maybe using an if ... else ... end statement or performing some HTTP request before to handle favicon images) and how to handle the above scenario?


Here's how to implement the idea you had in the original question.

The issue with this approach will be that your response times will include however long it takes for the other domain to respond to your request for the image. If that site is having issues, then your page wont load until the request times out.

<%
img_url = 'http://adomain.com/image.jpg'
res = Net::HTTP.get_response(URI.parse(img_url))
img_url = '[my alternate url]' unless res.code.to_i >= 200 && res.code.to_i < 400 #good codes will be betweem 200 - 399
%>

<%=image_tag img_url%>

The jQuery approach is a bit more involved. I'd suggest something along the following:

  • create an <img> tag with a transparent spacer image
  • in the page's javascript run a $.ajax call for the remote image
    • in the success callback replace the <img>'s src with the remote images's url
    • in the failure callback replace the <img>'s src with the fallback image's url

Unfortunately, I don't have time to generate the exact code for this right now.


You can't do this with Rails unless you fetch the image server-side before rendering the page. What you could do is fetch it in the client with a JavaScript and if there's trouble retrieving it, then switch to an alternative.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜