首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理类似于<link rel="stylesheet">的<?xml-stylesheet>?

处理类似于<link rel="stylesheet">的<?xml-stylesheet>?
EN

Stack Overflow用户
提问于 2017-01-06 08:55:54
回答 1查看 412关注 0票数 4

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

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

代码语言:javascript
复制
<!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并放在根目录中):

代码语言:javascript
复制
h1 { color: red; }

首先,在script.js中,我用link元素动态地附加了这个CSS:

代码语言:javascript
复制
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属性到达它:

代码语言:javascript
复制
link.addEventListener('load', function() {
  const stylesheet = link.sheet;
});

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

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

但是现在,如果样式表附加了<?xml-stylesheet>处理指令,我不能确定是否可以进行同样的操作:

代码语言:javascript
复制
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关联的样式表?

EN

回答 1

Stack Overflow用户

发布于 2017-01-07 03:07:17

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

您可以使用PerformanceObserver检查请求和加载的资源。迭代document的节点,检查.nodeType 7.nodeType 8,因为ProcessingInstruction节点可能具有comment .nodeType。从性能条目获取"resource"属性。对于href="URL"处的URL,解析过滤节点的.nodeValue,检查value是否等于性能条目的"resource",然后检查.styleSheet .href值是否等于解析的URL,以及解析的URL是否等于性能条目的"resource"属性值。如果为true,则迭代ProcessingInstruction节点上加载的styleSheet.cssRules.rules

代码语言:javascript
复制
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()来处理

内存不足,CPU繁忙,多个进程在运行

代码语言:javascript
复制
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,填充响应文本,将style元素的.textContent设置为调整后的css文本。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41497274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档