Search code examples
svg

Can a SVGStyleElement be disabled like an HTMLStyleElement can?


Short version:

Unlike the HTMLStyleElement the SVGStyleElement has no disabled property (according to the MDN docs)

Question: can a whole SVGStyleElement be disabled/toggled?

Longer playground version:

  • I can inject HTML in a DIV and the HTMLStyleElement remains a HTMLStyleElement and respects the disabled state.
    (there is a FOUC because onload=this.disabled=true kicks in after parsing)
    The disabled Toggle Button works as it should.

  • Injected in an SVG the HTMLStyleElement becomes a SVGStyleElement

    • The onload is ignored (the exact behaviour I want for my Web Component)

    • FireFox shows the state undefined on first load because there is no disabled property

    • but!! the disabled Toggle button works in Chromium, not in FireFox (and Safari??)

Question: Which Browsers are doing what right?

<template id=TEMPLATE>
  <style onload="this.disabled=true">
    body { background: red; }
    circle { fill:green; }
  </style>
  <circle cx="50%" cy="50%" r="45%"></circle>
</template>
<div id=DIV></div>
<svg id=SVG width="40" height="40"></svg>
<script>
let STYLE;// global
  function inject(id) {
    DIV.innerHTML=``;SVG.innerHTML=``;  // wipe all
    INNER.innerHTML=``;DISABLEDSTATE.innerHTML=``;
    id.innerHTML = TEMPLATE.innerHTML; // set innerHTML in DIV or SVG
    INNER.append(TEMPLATE.innerHTML); // show template HTML as text
    setTimeout(() => { // wait till DOM is fully updated
        STYLE = id.querySelector("style"); // get style tag in DIV or SVG
        DISABLEDSTATE.append(STYLE.constructor.name,' - disabled state: ',STYLE.disabled);
    })
  }
  function toggle(){
    STYLE.disabled = !STYLE.disabled;
    DISABLEDSTATE.innerHTML =``;
    DISABLEDSTATE.append(STYLE.constructor.name,' - disabled state: ',STYLE.disabled);
  }
</script>
<hr>
<button onclick="inject(DIV)">inject Template in DIV</button>
<button onclick="toggle()">toggle STYLE disabled state</button>
<button onclick="inject(SVG)">inject Template in SVG</button>
<hr><b>Injected HTML:</b><div id=INNER></div>
<b>Style disabled state:</b><div id=DISABLEDSTATE></div>


Solution

  • Chrome and Firefox have implemented disabled on SVGStyleElement for some time now.

    The SVG 2 specification says this about the style element

    SVG 2 ‘style’ element shall be aligned with the HTML5 ‘style’ element.