Almost every person in the web development community is aware of SVG (also referred to as Scalable Vector Graphics). SVG is nothing more than an image format (just like JPEG and GIF) used to define vector based graphics. However, SVG has some advantages over the other image formats, two of the most important ones are listed below:
- It can scale to any size without affecting the clarity of the image (except for very tiny images).
- SVG images can be created as well as edited using any text editor.
So, if you want to inject SVG into your projects there are several ways to do so. However, in this post we will discuss about injecting SVG with JavaScript. Probably you’ll be thinking – why should you inject SVG using JS? How does the implementation takes place?
Implementation of SVG Data Using JS
Let’s Get Started
As discussed above, you can implement SVG into your web project in different ways, each of which has its own pros and cons. When it comes to implementing SVG, we need to pay attention to mainly 3 variables HTTP requests, customisation capabilities of CSS and JS and browser support. Now if you want to meet these three variable requirements (and using Internet Explorer 9+ support), the most viable way is to make use of inline SVG <svg>
markup. Inline SVG is nothing but SVG markup that is added to the markup in the web pages.
Problems with Using Inline SVG
Inline SVG can bloat your web pages, particularly when you’re working on larger projects. Besides, managing inline SVG can give you a hard time, especially when you’re using PHP. For instance, in case you need to make certain changes, you’ll have to conduct a thorough search, so as to find the respective SVG markup. And then, you need to change the markup and save it. Next, you’ll have to find the relative CSS, and clear the cache and so on.
There are several other problems with inline SVG, the most important one being deferred loading capability and its effect on page-loading. What’s more, the inability to cache your HTML or XML markup will not let the SVG markup get cached by the browser.
These disadvantages can be eliminated by using JavaScript to inject the SVG data.
How to Use JavaScript to Integrate SVG?
Step 1 – Access your SVG code
You can choose to download SVG elements or design your own SVG elements. You can either save your SVG in .ai
(Illustrator) or .SVG
format or any other format you want to work with.
Let’s say, you’re working with an SVG file that is built with the help of Illustrator, then your code will look like:
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="95px" height="95px" viewBox="0 0 95 95" style="enable-background:new 0 0 95 95;" xml:space="preserve"> <style type="text/css"> <![CDATA[ .my-circle{fill:#EC0180C;} ]]> </style> <circle class="my-circle" cx="46.825" cy="48.016" r="32.954" .../> </svg>
Step 2 – Minify SVG and Make it Clutter-Free
After getting the SVG markup, make it clean and minify it. This can be done by adding the following line of code in the markup:
<svg><circle class="mycircle" cx="46.825" cy="48.016" r="32.954" .../></svg>
Step 3 – Integrating SVG Using JavaScript
Next, you’ll need to create a .js
document and save it with the name SVGinject.js
(or any other name as you deem perfect). First off, you’ll have to cache a variable in which the SVG needs to be injected. Here we are using unique ID element “logo” as the variable, and then we will add eventListener
to figure out when the document has loaded. Lastly, paste your SVG markup in the innerHTML content of the element. For example, use the code as follows:
var logo = document.getElementById("mylogo"); document.addEventListener('DOMContentLoaded', function(){ mylogo.innerHTML = 'SVG Code Will Come Here'; });
Now, to make the icon visible all we have to do is create an element using a corresponding ID, as follows:
<span id="mylogo"></span>
JavaScript will now integrate SVG into the newly created element, once the content of the document has loaded.
Injecting SVG Into Multiple Classes
In the last step in the process of implementing SVG using JS, we used a target element in the form of an unique ID – which is present only once in a single document. But, what if you want to integrate the same SVG into multiple elements using a class?
For example, in case you want the same icon to appear multiple times on a web page, use the following code:
document.addEventListener('DOMContentLoaded', function(){ var logo = document.querySelectorAll('.logo'); for (i = 0; i < logo.length; ++i) { logo[i].innerHTML = 'SVG Code Will Come Here'; } });
After including this code in your InnerHTML, any element with the class .logo, will get the SVG markup integrated in the form of its contents.
Integrating Multiple SVGs/Icons
Sometimes, you may feel the urge to make use of a lot of SVG content (such as icons). In such a case, your SVGinject.js
file will appear like this:
document.addEventListener('DOMContentLoaded', function(){ var icn1 = document.querySelectorAll('.icon1'); var icn2 = document.querySelectorAll('.icon2'); var icn3 = document.querySelectorAll('.icon3'); //icon 1 for (i = 0; i < icn1.length; ++i) { icn1[i].innerHTML = 'SVG Code Will Come Here'; } //icon 2 for (i = 0; i < icn2.length; ++i) { icn2[i].innerHTML = 'SVG Code Will Come Here'; } // icon 3 for (i = 0; i < icn3.length; ++i) { icn3[i].innerHTML = 'SVG Code Will Come Here'; } });
Conclusion
If you want to delay the loading of your SVGs until your web page gets loaded properly, then the most viable solution is to inject the SVG using JavaScript. Hopefully, reading this post will help you get a basic understanding of how the process of implementing SVGs via JS works.