Saturday, October 25, 2014

External SVG: Can I use Part 4

Previous: Inline SVG, CSS and defs: Can I use Part 3

External SVG file can be included inside HTML with one of the next methods:
  • <object type="image/svg+xml" data="circle_orange.svg" class="blockSize" />
  • <img src="circle_orange.svg" class="blockSize" />
  • <iframe src="circle_orange.svg" class="blockSize" />
  • <embed type="image/svg+xml" src="circle_orange.svg" class="blockSize" />
  • CSS background with svg file
Each method, except CSS background, is tested for browser support. In addition we investigated CSS support in <head> section of HTML page and style inlining in external SVG file.

All browsers (except that do not support SVG) showed good results and support external svg referencing.

While investigating render with browsers that do not support SVG, at first all went as expected. Here is the result for IE 7:

But then Android Mobile Browser 2.2 showed this: 

You can see the CSS code, which should not be shown. It is inlined in external SVG.
The suggestion falls in 3d section with iframe in both cases. To confirm the suggestion the page with iframe reference is created:
<!DOCTYPE html>
    <title>HTML5 SVG demo</title>
    <iframe src="circle_orange_defs.svg" class="blockSize"></iframe>

File circle_orange_defs.svg:
<svg xmlns="" xmlns:xlink="" 
      width="20" height="20">
        .orange_internal {
          fill: #FF9900;
          <circle id="circle_orange" cx="10" cy="10" r="8" stroke="grey" stroke-width="2" class="orange_internal" />
      <use xlink:href="#circle_orange" width="20" height="20" />
And Android 2.2 renders it as

As suggested old Android cannot clearly render iframe with external SVG, that contains inlined style.
We can use some tricks to fix it, but simple solution is not to use iframe for SVG at all, there are at least 4 alternatives to reference SVG file.

CSS support

All browsers that can render SVG support style in external files if they are inlined in SVG.
There is no possibility to apply HTML CSS from <head> section to external SVG file, because browser does not consider it as part of the DOM. This is the reason why one of the line with circles is black (lack of style).

Test results

Browsers that support SVG process external files without a problem. Android Mobile browser 2.2 has bad behaviour with <iframe>.

The results for desktop:
Chrome: 38, ..., 16 *
Internet Explorer: 11, 10, 9,  8, 7, 6
Firefox: 31, ..., 4, 3.6, 3.5
Safari: 8, 7, 6.1, 5.1

* - green - works as expected, red - does not support SVG 

The result for mobile devices:
Chrome Mobile: 37, ..., 31
Android Browser: 4.0, 2.2
Mobile Safari: 5.1, 5.02, 4.0.5, 4.0.4

In this test external reference with hash tag is not tested and will be done in future. There are some known problems with partial referencing (#) <img src="circle_orange.svg#circle" />. 

Next: SVG  fallback image without java-script.