Home » Javascript » how to count svg elements for performance tuning in javascript

how to count svg elements for performance tuning in javascript

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have a javascript web app which is dynamically graphing+animating various datasets in SVG, and want to do some performance tuning because there can be thousands of SVG elements. I am looking for a count of the visible or significant elements for comparison. My working but crude first attempt is below. Would like to at least get counts by each SVG element rather than the document-wide document.getElementsByTagName() call.

   let svgs = document.getElementsByTagName("svg"),
       totalChildren = 0,
       childCounts = [];

   for( let i=0; i<svgs.length; i++ ){
       let svg = svgs[i];
       totalChildren += svg.childElementCount;
       childCounts.push( svg.childElementCount );
   }

   let tags = [ "clipPath", "circle", "rect", "path", "text" ],
       tagMessage = "";
   tags.forEach( tagName => {
       tagMessage += ( document.getElementsByTagName(tagName).length + " ");
   });

   console.log( 'SVG element counts are: totalChildren='+ totalChildren, " SVG childElementCounts:", childCounts, " by tag:", tagMessage + tags );

Sample output:

SVG element counts are: totalChildren=2721 SVG childElementCounts: (6) [1312, 5, 30, 4, 4, 1366] by tag: 1313 1317 2673 21 11 clipPath,circle,rect,path,text

Answers: