I'm using Ruby on Rails v3..9 and I must see if a picture (during my situation a favicon.ico icon image) is effectively retrieved from an internet site and when not I must display a custom image.

To be able to retrieve the favicon.ico image associated with an internet site, in my opinion file I've:

image_tag "#/favicon.ico", :size => "16x16"

where web_site.link values are something similar to the followers:

http://stackoverflow.com/

http://world wide web.stackoverflow.com/

http://facebook.com/

...

How to see if a picture was discovered on an internet site (maybe utilizing an if ... else ... finish statement or carrying out some HTTP request before to deal with favicon images) and just how to handle above scenario?

Here's how you can implement the concept you'd within the original question.

The problem with this particular approach is going to be that the response occasions includes however lengthy it requires for that other domain to reply to your request the look. In the event that website is getting issues, your page wont load before the request occasions out.

<%

img_url = 'http://adomain.com/image.jpg'

res = Internet::HTTP.get_response(URI.parse(img_url))

img_url = '[my alternate url]' unless of course res.code >= 200 &lifier&lifier res.code < 400 #good codes is going to be betweem 200 - 399

%>

<%=image_tag img_url%>

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

  • create an <img> tag having a transparent spacer image
  • within the page's javascript operate a $.ajax demand the remote image
    • within the success callback replace the <img>'s src using the remote images's url
    • within the failure callback replace the <img>'s src using the fallback image's url

Regrettably, I do not have enough time to create the precise code with this at this time.

You cannot do that with Rails unless of course you fetch the look server-side before rendering the page. What you might do is fetch it within the client having a JavaScript and when there's trouble locating it, then switch to a different.