Why are SVG objects always drawn later?

2019-08-09 12:38发布

In my HTML5 page, I'm incorporating SVG with fallback the following way. Behind is a background :

<object type="image/svg+xml" data="simpleParallelogram.svg" width="284" height="460">
    <img src="simpleParallelogram_fallback.jpg" width="284" height="460">
</object>   

<img src="background.jpg">

No matter where I put the SVG object in the page (which is a very simple parallelogram), I always experience a delay in its displaying. The background is drawn, then the SVG pops up, resulting in a disgraceful stuttering load.

Any ideas why and how I can prevent it?

标签: html5 svg
1条回答
等我变得足够好
2楼-- · 2019-08-09 13:17

SVG object are not always drawn later. It depends on the way they are embbed in the HTML page. If you want an instant drawing of the SVG and a fallback without javascript, you have to use either :

The CSS background technique

The SVG will be referenced in the CSS. Because CSS is loaded in the head section, it will draw the SVG as it appears in the HTML code.

.my-element {
    background-image: url(fallback.png);
    background-image: 
    linear-gradient(transparent, transparent),
    url(image.svg);
}

More details on how to use this technique

The inline SVG with foreignObject technique

Because it's inline, the SVG will be drawn as it appears in the HTML code.

<svg>
    <switch>
        <g>
           /* Here the SVG code */
        </g>
        <foreignObject>
            /* Here the image fallback */
        </foreignObject>
    </switch>
</svg>

More details on how to use this technique

All the others SVG inclusion techniques, will result in a delay in the displaying of the SVG.

查看更多
登录 后发表回答