将 document.stylesheets 转换为 javascript 中的路径数组

Convert document.stylesheets into array of paths in javascript

我在 java-script 中有一段动态代码,用于分析页面上的样式表。我的大部分部件都在工作,但我有一个挂断...

我正在检查某些样式表是否存在的部分。 MDN 对此有这样的说法,“[StyleSheetList] 是一个类似数组的对象,但不能使用 Array 方法对其进行迭代。但是它可以......转换为数组。”它们包括一个示例,其中将对象转换为规则数组,但我没有看到获取路径的明确方法。它还说 "styleSheetList[index]" 是一种可以访问它的方式。我尝试创建这个函数,但它不起作用,总是返回 false...

function checkStyleSheet (styleSheetPath){
    var mysheets=document.styleSheets;
    for (var i = 0, max = mysheets.length; i < max; i++) {
        if (mysheets[i].href == styleSheetPath){
            return true;
        }
    }
    return false;
}

谢谢

JFiddle https://jsfiddle.net/3jsvbwrv/

编辑: console.log 的 mysheets[i] 就在 for 循环内 returns...

// CSSStyleSheet → http://example.com/example.css
CSSStyleSheet { 
    ownerRule: null,
    cssRules: CSSRuleList[1],
    type: "text/css",
    href: null,
    ownerNode: <style>,
    parentStyleSheet: null,
    title: "",
    media: Object[0],
    disabled: false 
}

编辑 2: 注意:在 if 语句中将 mysheets[i].href 更改为仅 mysheets[i] 并不能解决问题。 example.css 仍会被发现为假。

编辑 3: 我不认为它应该有任何影响,但以防万一它可能有用,或者提供更广泛的概述,或者帮助上下文......那里的 CSS 脚本是通过这个函数包含的,它是首先调用(已验证有效)...

function addStyleSheet (styleSheetPath){
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = styleSheetPath;
    document.getElementsByTagName("head")[0].appendChild(link);
}

我的最终目标是完成这项工作...

function requireStyleSheet (styleSheetPath){
    if (!checkStyleSheet(styleSheetPath)){
        addStyleSheet(styleSheetPath);
    }
}

编辑 4 我的测试 html:

<button onmousedown="addStyleSheet('htt://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css')">Step1‌​</button>
<button onmousedown="requireStyleSheet('http://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css')">S‌​tep 2</button>

编辑 5 正如一些测试人员指出的那样,代码按原样运行。事实证明,我的问题是在我的第二个函数尝试检查其存在之前,调用的文件尚未完成加载。

我 运行 我页面中的代码以有效的 CSS 文件作为参数,它返回 true。在您的示例中,它看起来好像您正在尝试加载 JS 文件而不是 CSS 文件:

<button onmousedown="addStyleSheet('http://momentjs.com/downloads/moment.min.js')">Step1‌​</button>
<button onmousedown="requireStyleSheet('http://momentjs.com/downloads/moment.min.js')">S‌​tep 2</button>

也许您可以考虑让 checkStyleSheet 检查哈希,而不是每次都循环遍历每个样式 sheet。

我知道这是一个老问题,但它也是我来找同样的东西时的第一个搜索结果。 Javascript 我想有一些新技巧,因为这是我现在正在做的事情:

[].slice.call(document.styleSheets).map(e => e.href)