Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptHow to import a SVG file in JavaScript ?

How to import a SVG file in JavaScript ?

In this article, we are going to see and use different ways of using SVGs ( Scalable Vector Graphics).

Method 1: The quickest way using HTML <img> element.

Syntax: 

 <img src='logo.svg' alt="some file"  height='100'
width='100' style="color:green;"/>

Embedding an SVG through the <img> element, you need:

  • src attribute
  • height attribute (if your SVG has no inherent aspect ratio)
  • width attribute  (if your SVG has no inherent aspect ratio)

Pros:

  • Easy and quick implementation.
  • Make the SVG image into a hyperlink by nesting <img> & <a> HTML element
  • Caching of SVG file, hence reduced loading time.

Cons:

  • Manipulation of SVG file cannot be done.
  • You can only use inline CSS to style your SVG.
  • Cannot use CSS pseudo-classes to style the SVG.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  <body>
    <img
      src=
      alt="gfg-logo"
      height="100"
      width="100"
      style="background-color: green"
    />
  </body>
</html>


Output :

SVG file using HTML <img> element

Method 2: Using SVG as an <object>

Syntax: 

<object type="image/svg+xml" data="logo.svg" class="logo">
  Logo
</object>

Embedding a SVG via a <object> element requires:

  • type attribute
  • data attribute
  • class attribute ( if using external/internal CSS )

Pros :

  • You can use external/internal CSS to style SVG.
  • Easy and quick implementation.
  • Will work great with caching.

Cons :

  • To use an external stylesheet, you need to use an <style> element inside the SVG file.
  • Not so familiar with syntax and implementation.

HTML code:

HTML




<!DOCTYPE html>
<html lang="en">
<body>
  <object type="image/svg+xml" 
          data=
          class="logo">
    GFG Logo
  </object>
   
</body>
   
</html>


CSS code:The following is the content for the “styles.css” file used in the above code.

.logo {
  height: 100;
  width: 100;
}

Output :

SVG file using HTML <object> element

Method : Embedding an SVG with an <iframe>

Syntax : 

<iframe src="logo.svg" width="500" height="500">

</iframe>

Embedding a SVG via <iframe> element requires

  • src attribute
  • height attribute (if your SVG has no inherent aspect ratio)
  • width attribute  (if your SVG has no inherent aspect ratio)

Pros :

  • Quick and easy implementation.
  • Same as <object> element.

Cons :

  • You can’t use JavaScript to manipulate the SVG.
  • Caching is not great.

HTML code :

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, 
                                   initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
  </head>
  
  <body>
    <iframe
      src=
      width="150"
      height="150">
    </iframe>
  </body>
</html>


Output :

RELATED ARTICLES

Most Popular

Recent Comments