处理<! - ?xml-stylesheet - >类似于<link rel =“stylesheet”/>?

时间:2017-01-06 00:55:54

标签: javascript css xhtml processing-instruction cssom

在调查使用<?xml-stylesheet>处理指令附加CSS的优缺点时,我遇到了一些问题。

假设我们有一个简单的XHTML文档(以application/xhtml+xml MIME类型提供并在Web浏览器中查看):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>A sample XHTML document</title>
    <script type="application/javascript" src="/script.js"></script>
  </head>
  <body>
    <h1>A heading</h1>
  </body>
</html>

然后我们有一个外部CSS文件(让它命名为style.css并放在根目录中):

h1 { color: red; }

首先,在script.js中,我使用link元素动态附加此CSS:

const link = document.createElement('link');
Object.entries({rel: 'stylesheet', type: 'text/css', href: '/style.css'})
      .forEach(([name, value]) => link.setAttribute(name, value));
document.head.appendChild(link);

然后脚本一直等到样式表完成加载并通过sheet属性到达它:

link.addEventListener('load', function() {
  const stylesheet = link.sheet;
});

在此之后,脚本可以操作此样式表,例如:

stylesheet.cssRules.item(0).style.color = 'green';      // modify an existing rule
stylesheet.insertRule('body { background: #ffc; }', 1); // insert a new rule

但是现在,如果使用<?xml-stylesheet>处理指令附加样式表,我无法弄清楚是否可以进行相同的操作:

const pi = document.createProcessingInstruction('xml-stylesheet',
           'href="/style.css" type="text/css"');
document.insertBefore(pi, document.documentElement);

首先,PI似乎没有load事件,因此脚本无法知道样式表何时准备就绪。其次,没有sheet属性,因此您无法调用pi.sheet来访问样式表。

有没有办法克服这些困难并从脚本转到与<?xml-stylesheet> PI关联的样式表?

1 个答案:

答案 0 :(得分:0)

  

首先,PI似乎没有加载事件,因此脚本无法知道何时   样式表已准备就绪。

您可以使用PerformanceObserver检查请求和加载的资源。迭代document的节点,检查.nodeType 7.nodeType 8,因为ProcessingInstruction节点可能有comment {{1 }}。从性能条目中获取.nodeType属性。解析"resource"处的网址的已筛选节点的.nodeValue,检查值是否等于效果条目的href="URL",然后检查"resource" .styleSheet值是否等于解析的URL,如果解析的URL等于性能条目.href属性值。如果"resource",则迭代在true节点加载的{​​{1}}的{​​{1}}或.cssRules

.rules

plnkr http://plnkr.co/edit/uXfSzu0dMDCOfZbsdA7n?p=preview

您还可以使用styleSheetProcessingInstruction来处理

  

低RAM,忙CPU,许多进程正在运行

window.onload = () => {
  let resource;
  const observer = new PerformanceObserver((list, obj) => {
    for (let entry of list.getEntries()) {
      for (let [key, prop] of Object.entries(entry.toJSON())) {
        if (key === "name") {
          resource = prop;
          var nodes = document.childNodes;
          _nodes: for (let node of nodes) {
            if (node.nodeType === 7 || node.nodeType === 8 
            && node.nodeValue === pi.nodeValue) {
              let url = node.baseURI 
                        + node.nodeValue.match(/[^href="][a-z0-9/.]+/i)[0];
              if (url === resource) {
                observer.disconnect();
                // use `setTimeout` here for
                // low RAM, busy CPU, many processes running
                let stylesheets = node.rootNode.styleSheets;
                for (let xmlstyle of stylesheets) {
                  if (xmlstyle.href === url && url === resource) {
                    let rules = (xmlstyle["cssRules"] || xmlstyle["rules"]);
                    for (let rule of rules) {
                      // do stuff
                      console.log(rule, rule.cssText, rule.style, xmlstyle);
                      break _nodes;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  });

  observer.observe({
    entryTypes: ["resource"]
  });

  const pi = document.createProcessingInstruction('xml-stylesheet',
    'href="style.css" type="text/css"');
  document.insertBefore(pi, document.documentElement);

}

plnkr http://plnkr.co/edit/AI4QZiBUx6f1Kmc5qNG9?p=preview

或者,使用MutationObserversetTimeout()来请求window.onload = function() { let observer = new MutationObserver(function(mutations) { console.log(mutations) for (let mutation of mutations) { for (let node of mutation.addedNodes) { if (node.nodeName === "xml-stylesheet") { let url = node.baseURI + node.nodeValue.match(/[^href="][a-z0-9/.]+/i)[0]; setTimeout(function() { for (let style of document.styleSheets) { if (style.href === url) { observer.disconnect(); // do stuff console.log(style) } } // adjust `duration` to compensate for device // low RAM, busy CPU, many processes running }, 500) } } } }); observer.observe(document, { childList: true }); const pi = document.createProcessingInstruction('xml-stylesheet', 'href="style.css" type="text/css"'); document.insertBefore(pi, document.documentElement); } 文件,创建XMLHttpRequest()元素并将其附加到fetch(),使用响应文本执行操作,设置{已将.css元素{1}}调整为<style>文字。