RE: Adding SVG via JavaScript (problem with the 'use' element)

Jan Tošovský, modified 6 Years ago. Liferay Master Posts: 576 Join Date: 7/22/10 Recent Posts
When adding SVG into DOM via JavaScript I am unable to add <use> element:
<div id="parent"></div>
<script>
    var parentElement = document.getElementById("parent");
    var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    var useElement = document.createElementNS("http://www.w3.org/2000/svg", "use");
    useElement.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "image.svg");
    svgElement.appendChild(useElement);
    parentElement.appendChild(svgElement);
</script>
This code just adds an empty SVG element. That <use> element is completely missing. There is no error in the browser console.
However, when this code is put into any static HTML page (not Liferay portal), it works fine and that <use> element is added correctly.
On the contrary, I've tried adding <style> element into SVG and it works even in LR.
Is there any element filter applied on Liferay side?
LR 7.1.2 GA3/tomcat 9/Chrome
thumbnail
Christoph Rabel, modified 6 Years ago. Liferay Legend Posts: 1555 Join Date: 9/24/09 Recent Posts
Maybe you hit an issue with svg4everybody. We had several problems with that script in the past.
To check, you could try to disable it:
Liferay.Data.ICONS_INLINE_SVG = false;
This line has to be added below the header, but above the bottom of the page.
Jan Tošovský, modified 6 Years ago. Liferay Master Posts: 576 Join Date: 7/22/10 Recent Posts
Hi Christoph, that settings really helped in my case so it is related. However, it broke rendering all Liferay SVG icons (referenced as e.g. 'icons.svg#ellipsis-v') so I cannot  use this approach.
I'll most likely insert the SVG content inline to avoid using the <use> element, although it means more code.
thumbnail
Christoph Rabel, modified 6 Years ago. Liferay Legend Posts: 1555 Join Date: 9/24/09 Recent Posts
I asked my colleague what we did to resolve the issue.
The svg has to be a file url and then you need to use it the following way: (you need both data-href and xlink href)

<svg class="svg-logo" width="12px" height="12px"> 
   <use data-href="${images_folder}/sprite.svg#streamline-caret-down" xlink:href="${images_folder}/sprite.svg#streamline-caret-down"></use> 
</svg>
hth
And I suggest, you open a bug at issues.liferay.com.