How can I detect failure to load an image in Elm

北城余情 提交于 2020-01-13 11:04:24

问题


How can I detect that an image was failed to be load in Elm?

I use img [ src "/path/to/image" ] and would like to know if the image failed to load. In plan old JavaScript I would register to onError event of img but I don't see onError in Elm.


回答1:


You can use Html.Events.on to capture an image load error.

You will need a Msg value to indicate that the image failed. Here I'll call that ImageError:

img [ src "/path/to/image", on "error" (Json.Decode.succeed ImageError) ] []

The use of Json.Decode.succeed may look confusing in this context (after all, you're trying to capture an error, so what is succeed doing there?), but that's just part of the JSON decoding package. It basically means to ignore the error javascript value passed as the first parameter by the DOM event and use the ImageError Msg.

Here is an example of capturing the error event.

And here is another example which captures both the error and load events. You can change the image src to a good or bad URL to see what happens in either case.



来源:https://stackoverflow.com/questions/44864043/how-can-i-detect-failure-to-load-an-image-in-elm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!