简体   繁体   English

使用 JavaScript 从外部文件读取 CSS?

[英]Read CSS from external file using JavaScript?

I'd like to be able to run a regex over all the CSS files that are loaded on a page for an internal tool.我希望能够对加载到内部工具页面上的所有 CSS 文件运行正则表达式。 This allows me to lint the CSS files and check for any conflicting declarations.这允许我检查 CSS 文件并检查是否有任何冲突的声明。

This works fine for local files by iterating over document.stylesheets and getting the values of cssRules .通过迭代document.stylesheets并获取cssRules的值,这适用于本地文件。

However, for CSS that is loaded from external sites such as Typekit, Google Fonts etc returns null for cssRules (see image).但是,对于从外部网站,如Typekit,谷歌字体等的回报加载CSS nullcssRules (见图片)。

css规则

I tried using JSONP to get the file, but it returns an invalid token as it is presumably expecting JSON and is getting CSS in response.我尝试使用 JSONP 来获取文件,但它返回一个无效的令牌,因为它可能期待 JSON 并且正在获取 CSS 作为响应。 Is there a way around this that I have not considered yet?有没有我还没有考虑过的解决方法?

For completeness, here is the JSONP test I tried:为了完整起见,这是我尝试过的 JSONP 测试:

$.ajax({
    type: 'GET',
    url: "path/to/file.css",
    jsonp: "callback",
    dataType: "jsonp",
    success: function(response) {
        var test = JSON.stringify(response);
        console.log(test);
    }
});

Is it possible to get the CSS from these stylesheets as a string which I can pass through my regex?是否可以从这些样式表中获取 CSS 作为字符串,我可以通过我的正则表达式传递它?

try to use complete css link and just use url attribute for ajax.尝试使用完整的 css 链接,只为 ajax 使用 url 属性。

Demo : jsFiddle演示: jsFiddle

$.ajax({
    url:"//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap-theme.min.css"
})
.done(function(result){
    $('.style').html(result);
});


    
.style {
  max-width: 300px;
  max-height: 300px;
  overflow:auto;
<div class="style"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM