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

Handling <?xml-stylesheet> similar to <link rel="stylesheet">?

提问人: 提问时间:1/6/2017 最后编辑:BoltClock 更新时间:1/8/2017 访问量:571

问:

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

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

<!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.jslink

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 似乎没有事件,因此脚本无法知道样式表何时准备就绪。其次,没有类似属性的东西,所以你不能调用来访问样式表。loadsheetpi.sheet

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

javascript css xhtml 处理指令 cssom

评论

0赞 guest271314 1/6/2017
您想使用处理指令实现什么?
0赞 1/6/2017
@guest271314,我正在研究使用 .<?xml-stylesheet>
0赞 guest271314 1/6/2017
“这个对象没有任何事件,它没有任何属性来获取它的样式表。”不确定问题是什么?您是否正在尝试获取并解析 a 加载 ?您能否包括您尝试过的内容,并在问题中描述需求?StyleSheetxhtmldocumentxhtmldocument
0赞 Mr Lister 1/6/2017
实际上,我认为您根本无法使用处理器指令“做任何事情”。如果您需要对样式表的加载进行这种级别的控制,请使用<link>。另一方面,如果你只需要知道所有样式表何时完成加载,你可以使用 ...window.onload
0赞 1/6/2017
@MrLister,我的脚本在发射很久之后插入了。<!xml-stylesheet>window.onload

答:

0赞 guest271314 1/7/2017 #1

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

您可以使用它来检查请求和加载的资源。迭代 的节点 ,检查 或 ,因为节点可以有 。从性能条目中获取属性。解析 URL 的过滤节点,检查 value 是否等于性能条目,然后检查 value 是否等于解析的 URL,以及解析的 URL 是否等于性能条目属性值。如果 ,则迭代 或 加载到节点。PerformanceObserverdocument.nodeType7.nodeType8ProcessingInstructioncomment.nodeType"resource".nodeValuehref="URL""resource".styleSheet.href"resource"true.cssRules.rulesstyleSheetProcessingInstruction

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/uXfSzu0dMDCOfZbsdA7n?p=preview

您还可以使用 ,来处理MutationObserversetTimeout()

RAM低,CPU繁忙,运行许多进程

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);

}

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


或者,使用或请求文件,创建元素并将其附加到,对响应文本做事,将元素集设置为调整后的文本。XMLHttpRequest()fetch().css<style>document.textContentstylecss

评论

0赞 1/7/2017
不幸的是,只能知道资源(例如)何时被加载,即浏览器引擎何时接收到它的所有字节。但是它无法判断新样式表何时真正添加到列表中,并且其属性(例如可用于脚本)的样式表。PerformanceObserverstyle.cssdocument.styleSheetscssRules
0赞 1/7/2017
在功能强大的设备上,没有问题。观察者“捕获”一个加载的 CSS 文件,并且它被添加到列表中的速度如此之快,以至于近期调用 返回已经更新的带有新样式表的列表。但是在功能低(RAM低,CPU繁忙,许多进程正在运行)的设备上测试代码,我发现样式表没有及时调用。此调用返回旧的样式表列表,并且在其中找不到请求的样式表。仅在更新一两秒后。document.styleSheetsdocument.styleSheetsdocument.styleSheets
0赞 1/7/2017
我认为真正的解决方案可能是直接观察并在添加新样式表时捕获事件。但是我不知道该怎么做(除了使用)。document.styleSheetssetInterval
0赞 guest271314 1/8/2017
@HydrochoerusHydrochaeris “但是在功能低(RAM低、CPU繁忙、许多进程正在运行)的设备上测试代码,我发现样式表没有及时调用document.styleSheets” 您可以在 either 或 approach 中使用。调整以补偿特定设备。setTimeout()PerformanceObserverMutationObserverdurationsetTimeout