Do I use , <>, >

2018-12-31 12:15发布

Should I use <img>, <object>, or <embed> for loading SVG files into a page in a way similar to loading a jpg, gif or png?

What is the code for each to ensure it works as well as possible? (I'm seeing references to including the mimetype or pointing to fallback SVG renderers in my research and not seeing a good state of the art reference).

Assume I am checking for SVG support with Modernizr and falling back (probably doing a replacement with a plain <img> tag)for non SVG-capable browsers.

10条回答
时光乱了年华
2楼-- · 2018-12-31 13:00

Use srcset

Most current browsers today support the srcset attribute, which allows specifying different images to different users. For example, you can use it for 1x and 2x pixel density, and the browser will select the correct file.

In this case, if you specify an SVG in the srcset and the browser doesn't support it, it'll fallback on the src.

<img src="logo.png" srcset="logo.svg" alt="My logo">

This method has several benefits over other solutions:

  1. It's not relying on any weird hacks or scripts
  2. It's simple
  3. You can still include alt text
  4. Browsers that support srcset should know how to handle it so that it only downloads the file it needs.
查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 13:01

If you need your SVGs to be fully styleable with CSS they have to be inline in the DOM. This can be achieved through SVG injection, which uses Javascript to replace a HTML element (usually an <img> element) with the contents of an SVG file after the page has loaded.

Here is a minimal example using SVGInject:

<html>
<head>
  <script src="svg-inject.min.js"></script>
</head>
<body>
  <img src="image.svg" onload="SVGInject(this)" />
</body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the file provided in the src attribute. This works with all browsers that support SVG.

Disclaimer: I am the co-author of SVGInject

查看更多
何处买醉
4楼-- · 2018-12-31 13:05

The best option is to use SVG Images on different devices :)

<img src="your-svg-image.svg" alt="Your Logo Alt" onerror="this.src='your-alternative-image.png'">
查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 13:09

This jQuery function captures all errors in svg images and replaces the file extension with an alternate extension

Please open the console to see the error loading image svg

(function($){
  $('img').on('error', function(){
    var image = $(this).attr('src');
    if ( /(\.svg)$/i.test( image )) {
      $(this).attr('src', image.replace('.svg', '.png'));
    }
  })  
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="https://jsfiddle.net/img/logo.svg">

查看更多
登录 后发表回答