DOMツリーが完了しないと、DOM操作はうまくいかないが、この程度だとbodyの最後にscriptを書けば問題ないようだ。
<!DOCTYPE html> <html> <head><title>SVG Test</title></head> <body> <h1>Hello SVG</h1> <script> const svgNS = "http://www.w3.org/2000/svg"; var body = (document.getElementsByTagName("body"))[0]; var svg = document.createElementNS(svgNS, "svg"); svg.setAttribute("width", "100"); svg.setAttribute("height", "100"); svg.setAttribute("viewBox", "0 0 100 100"); var circle = document.createElementNS(svgNS, "circle"); circle.setAttribute("cx", "50"); circle.setAttribute("cy", "50"); circle.setAttribute("r", "20"); circle.setAttribute("stroke", "black"); circle.setAttribute("fill", "red"); svg.appendChild(circle); body.appendChild(svg); </script> </body> </html>
document.addEventListener('DOMContentLoaded', () => {/* ... */}) とすれば、DOM構築完了イベントでコールバックを実行できる。が、既にイベントが発行済みだとコールバックが実行されないかも知れない。