title: MutationObserver and Shadow DOM
body: <p>I'm using Polymer's ShadowDOM and <code>MutationObserver</code> polyfills and need to:</p>
  
  <ul>
  <li>Detect when a <code>HTMLCanvasElement</code> is inserted so that I can perform layout (its width and height are undetermined through <code>offsetWidth</code> / <code>offsetHeight</code> when detached from the DOM tree)</li>
  <li>Detect when the element is removed so I can halt its <code>requestAnimationFrame</code> loop</li>
  </ul>
  
  <p>Traditionally, without Shadow DOM, this works as follows:</p>
  
  <ol>
  <li>Attach <code>MutationObserver</code> to <code>document.body</code> and perform <code>querySelectorAll</code> for any canvas elements</li>
  <li>Perform some method, e.g. <code>layoutNode</code> on these elements</li>
  <li>If in the animation loop <code>document.body.contains(node)</code> returns <code>false</code>, then the node has been removed from the DOM</li>
  </ol>
  
  <p>When using Shadow DOM I can get around the shadow dom boundaries by performing (what seems to be very inefficient) scans across all elements in the DOM that have roots which have been added, and performing <code>layoutNode</code> on any shadow dom nodes inheriting from <code>HTMLCanvasElement</code>.</p>
  
  <p>How do I check from the animation loop of the canvas that this node is still in the DOM tree?</p>
  
  <p>Is there a better API to use for detecting when a DOM node has been inserted?</p>
  
  <p>(NB. MutationEvents are unavailable using Polymer's CustomElements polyfill.)</p>