MutationObserver and Shadow DOM

I'm using Polymer's ShadowDOM and MutationObserver polyfills and need to:

  • Detect when a HTMLCanvasElement is inserted so that I can perform layout (it's width and height are undetermined through offsetWidth / offsetHeight when detached from the DOM tree)
  • Detect when the element is removed so I can halt its requestAnimationFrame loop

Traditionally, without Shadow DOM, this works as follows:

  1. Attach MutationObserver to document.body and perform querySelectorAll for any canvas elements
  2. Perform some method, e.g. layoutNode on these elements
  3. If in the animation loop document.body.contains(node) returns false, then the node has been removed from the DOM

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 layoutNode on any shadow dom nodes inheriting from HTMLCanvasElement.

How do I check from the animation loop of the canvas that this node is still in the DOM tree?

Is there a better API to use for detecting when a DOM node has been inserted?

(NB. MutationEvents are unavailable using Polymer's CustomElements polyfill.)

Answers


I can use the following function attached to a Node to check whether the node is eventually rooted (through multiple shadow dom boundaries) at a given document, or the current document if no document is specified. This should be as efficient as a JS-based root.contains(node) call.

Object.defineProperty(Node.prototype, 'isAttachedToDocument', {
    configurable: true,
    enumerable: false,
    writable: true,
    value: function(document) {
        document = document || window.document;
        var el = this;
        while(el.parentNode || el.host) el = el.parentNode || el.host;
        return (el.impl || el) === document;
    }
});

Need Your Help

Create XML XSL table from nodes with multiple attributes

html xml table xslt

I want to create a HTML table with XSL based on the following XML sheet. The goal is to create a table with all the company names and all their product names.

Max/min latitude of map tile map

google-maps openstreetmap mapquest

I'm trying to build a map based on a center point lat/long, the map will always be a fixed size say 1024 by 1024. The user can chance the center point and zoom.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.