The best solution won't need to be recoded when Safari and IE finally support webp, webm. Can javascript detect a failure to load a format and request the fallback image or media?
After further research I found: https://modernizr.com/
It's tests for the presence of features without hardcoding specific browsers. One of those features is webp. Not sure if it supports test for webm though.