Anwar Hussain

Anwar Hussain

Front-End Web Developer - HTML5, CSS3, JavaScript, React, VueJS, Git

Inline SVG icon: Inject SVG into HTML using JavaScript

You might be wondering how to implement SVG icon into your web page. The best way to put SVG element into an HTML document is inline SVG. Meaning the SVG code have to be placed inside the HTML. But often a complex graphic contains multiple lines of SVG code which might bloat your HTML document. Moreover, there could have multiple icons or graphical elements you need to put into a single web page. So writing all those SVG codes directly into markup is not efficient technique. If you do so this may save you one additional HTTP request but when you’ll come back to edit the same document after a while you may face difficulty to find a particular icon which you may want to change. Also, your document will be so long- you’ll easily get lost scrolling down.

So I want to show you a technique to inject SVG elements inside HTML document using JavaScript. Mostly I use this technique for injecting SVG icons into my web page. Before getting started I want you to get ready all your SVG files into a separate folder. Using grunt-svg-inject plugin, you’ll be able to create a single JS file which will inject SVG codes into the document to where it is attached. This JavaScript file includes all your SVG codes extracted from all svg files.

Necessary tools

You must have Node.js installed in your computer and optionally basic npm skill. Don’t worry if you are not familiar with npm, I will walk you through. Npm comes with Node.js. I will discuss regarding npm and build tools in a separate blog post.

To be sure whether Node.js installed properly or not, run those commands from the terminal:

node -v
npm -v

You’ll see the current version numbers of node and npm.

Make your project ready

Open terminal from your project folder or create a new folder anywhere in your computer and open terminal window from that place. Windows users can press Shift and right click to see “Open command window here” in the context menu.

npm init -y

npm init command creates package.json file and -y for the positive answer to all default prompts.

npm install -g grunt-cli

The above command will install grunt-cli (grunt command line interface) globally (-g flag) into your machine. This will put the grunt command in your system path, allowing it to be run from any directory. Avoid this step if you already have installed grunt-cli.

Install necessary grunt packages

npm install --save-dev grunt

Grunt is an npm plugin which will be installed locally into your project and be saved into “package.json” file under devDependency

npm install --save-dev grunt-svg-inject

grunt-svg-inject plugin will be installed and saved into “package.json” file.

Grunt configuration file

Now you need to create Gruntfile.js in the root of your project where package.json file is situated. If you want to know more about Gruntfile, please read their getting started.

The “wrapper” function

Every Gruntfile (and gruntplugin) uses this basic format, and all of your Grunt code must be specified inside this function:

module.exports = function(grunt) {
  // Do grunt-related things in here
};

Open the Gruntfile with your favorite text editor and write this function.

Project and task configuration

In the wrapper function, you need to specify grunt-svg-inject plugin configuration like bellow:

grunt.initConfig({
 svginject: {
    all : {
      options: {},
      files: {
         'dest/SVGinject.js': ['svgs/*.svg'],
      }
    }
  }
});

You can name it anything you want, this will be your command for execution of the task. I call it svginject here. Let’s go through the above config: there are two parts in the files key separated by a colon, left side is for output and right side is for input which will pass through the plugin. So, If you have all the SVG icons in svgs folder, you will get a JavaScript file created in dest directory called SVGinject.js. Also if you don’t have dest directory, it’ll be created. Leave the options key as a blank object.

Loading Grunt plugins and tasks

Last but not the least, you need to load the grunt task in the wrapper function.

// Load the plugin that provides the "svginject" task.
grunt.loadNpmTasks('grunt-svg-inject');
The Gruntfile

Now, the whole configuration file will look like:

// Gruntfile.js
module.exports = function(grunt) {
  grunt.initConfig({
    svginject: {
      all : {
        options: {},
        files: {
          'dest/SVGinject.js': ['svgs/*.svg'],
        }
      }
    }
  });

  grunt.loadNpmTasks('grunt-svg-inject');
};

Building the JavaScript file

Open terminal window and run the following command:

grunt svginject

Your JS file will be ready in “desk” folder.

An example will make those steps much easier

Using the above config, let’s go through an example. Say the folder “svgs” contains 3 .SVG files – icon1.svg, icon2.svg and icon3.svg.

Those SVG files contain something this:

<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>

SVGinject will then create a single JavaScript file at “dest/SVGinject.js” with the following (including the comments and in this spaced format):

document.addEventListener('DOMContentLoaded', function(){
 
 
// // SVG icon1 
var SVG_icon1 = document.querySelectorAll('.svg-icon1');
 
for (i = 0; i < SVG_icon1.length; ++i) {
SVG_icon1[i].innerHTML = '<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>';
}
 
// // SVG icon2 
var SVG_icon2 = document.querySelectorAll('.svg-icon2');
 
for (i = 0; i < SVG_icon2.length; ++i) {
SVG_icon2[i].innerHTML = '<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>';
}
 
// SVG icon3 
var SVG_icon3 = document.querySelectorAll('.svg-icon3');
 
for (i = 0; i < SVG_icon3.length; ++i) {
SVG_icon3[i].innerHTML = '<svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg>';
}
 
 
});

To include those SVGs in HTML, all you would do is this:

<span class="svg-icon1"></span>
<span class="svg-icon2"></span>
<span class="svg-icon3"></span>

Inline SVG markup will then be appended to those elements. So if the script is included in that document, the above would result in this:

<span class="svg-icon1"><svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg></span>
<span class="svg-icon2"><svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg></span>
<span class="svg-icon3"><svg><circle fill="#EC008C" cx="46.921" cy="57.107" r="31.759"/></svg></span>

Note that it supports multiple classes so the below would also work :

<span class="svg-icon1"></span>
<span class="svg-icon1"></span>
<span class="svg-icon1"></span>

Wrapping up

Now you can call SVGinject.js file to your project’s HTML files. Please comment bellow if you have something to ask, suggest or have found mistakes.

Thanks
Anwar H.

If you have enjoyed this post and have some feelings to share, please comment below or drop few lines!

2 thoughts on this post. Leave yours!

Leave a Reply