Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

asp.net - SVG for images in browsers with PNG fallback

I'm looking to use SVG versions of a company logo on a website. At present, all current versions of major browsers (IE, Safari, Chrome, Firefox, Opera) support SVG, so this doesn't seem crazy. However, old browsers are still out there, so I need to fall back to PNG support.

The obvious solution is to put the SVG content in an object tag like so (forgive the inline styles...):

<object data='logo.svg' style='height:3em' >
    <img src='logo.png' style='height:3em' />
</object>

Which in theory should render the object if possible, or else render the img. However, Chrome doesn't like this and applies the height style to the object itself but not the SVG, so I end up with a little iframe-like box with scrollbars, showing a huge logo.

Another solution would be to use the PNG as the img source, and then swap it out at render time with the SVG source with javascript, if I think I'm running on a SVG-capable browser. This is not ideal because the PNG will still get downloaded, and I'm not confidant I can properly detect SVG support. Unfortunately, jQuery doesn't seem to have a SVG-detect feature.

Finally, since my website is deployed with ASP.NET, I could inspect the user agent string before serving the page, and specify the img source depending on whether I think it will support SVG. But this also has the potential problem that I am not confidant I can make the right call.

What is the preferred way of doing SVG for images?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an old question, but here is another solution:

  1. Download a version of Modernizr that is trimmed down to just testing SVG (assuming that’s the only test you need).

  2. Run the test. If it passes, put in the SVG. If it fails, put in the bitmap. Essentially:

    if (!Modernizr.svg) { 
        $("#logo").css("background-image", "url(fallback.png)"); 
    }
    

SVG is a perfect use case for Modernizr, because there is no simple native way to provide a fallback.

Note: The browser don't load both (png and svg) versions.

For the record: the only reason you would need a fallback for SVG these days if you have to support IE 8 and down, or older Android.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...