1/** 2@license 3Copyright (c) 2016 The Polymer Project Authors. All rights reserved. 4This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt 5The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt 6The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt 7Code distributed by Google as part of the polymer project is also 8subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt 9*/ 10 11/* 12Example library for adding document-level styles to ShadyCSS 13 14After DOMContentLoaded, synchronously add all document document level styles. 15Then, start a MutationObserver for dynamically added styles. 16 17Caveat: ShadyCSS will add a `scope` attribute to styles it controls, so do not add those styles. 18*/ 19(function() { 20 'use strict'; 21 22 const CustomStyleInterface = window.ShadyCSS.CustomStyleInterface; 23 24 function shouldAddDocumentStyle(n) { 25 return n.nodeType === Node.ELEMENT_NODE && n.localName === 'style' && !n.hasAttribute('scope'); 26 } 27 28 function handler(mxns) { 29 for (let i = 0; i < mxns.length; i++) { 30 let mxn = mxns[i]; 31 for (let j = 0; j < mxn.addedNodes.length; j++) { 32 let n = mxn.addedNodes[j]; 33 if (shouldAddDocumentStyle(n)) { 34 CustomStyleInterface.addCustomStyle(n); 35 } 36 } 37 } 38 } 39 40 const observer = new MutationObserver(handler); 41 42 document.addEventListener('DOMContentLoaded', () => { 43 const candidates = document.querySelectorAll('custom-style'); 44 for (let i = 0; i < candidates.length; i++) { 45 const candidate = candidates[i]; 46 if (shouldAddDocumentStyle(candidate)) { 47 CustomStyleInterface.addCustomStyle(candidate); 48 } 49 } 50 observer.observe(document, {childList: true, subtree: true}); 51 }); 52 53 window.documentStyleFlush = () => {handler(observer.takeRecords())}; 54})();