Access CSS file contents via JavaScript

后端 未结 6 747
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 04:29

Is it possible to get the entire text content of a CSS file in a document? F.ex:




        
相关标签:
6条回答
  • 2020-11-30 05:14

    If you used XMLHttpRequest to load the page you could get acces to those files without having to load them a second time.

    it's preferable to not duplicate ton reduce bandwidth and efficiency.

    what if the css is generated dynamically and is different depending on the time it is requested?

    0 讨论(0)
  • 2020-11-30 05:20

    With that specific example (where the CSS is on the same domain as the page), you could read the file as text via ajax:

    $.ajax({
        url: "/path/to/file.css",
        dataType: "text",
        success: function(cssText) {
            // cssText will be a string containing the text of the file
        }
    });
    

    If you want to access the information in a more structured way, document.styleSheets is an array of the style sheets associated with the document. Each style sheet has a property called cssRules (or just rules on some browsers), which is an array of the text of each rule in the style sheet. Each rule has a cssText property. So you could loop through those, e.g.:

    $.each(document.styleSheets, function(sheetIndex, sheet) {
        console.log("Looking at styleSheet[" + sheetIndex + "]:");
        $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
            console.log("rule[" + ruleIndex + "]: " + rule.cssText);
        });
    });
    

    Live example - That example has one stylesheet with two rules.

    0 讨论(0)
  • 2020-11-30 05:23

    Yep, you can use $.get.

    Example:

    $.get('/path/to/css/file.css', function (resp) {
        // resp now should contain your CSS file content.
    
    });
    
    0 讨论(0)
  • 2020-11-30 05:28

    you could load the content with a simple ajax get call, if stylesheet is included from the same domain

    Edit after your update:
    I tried this code (on FX10) as a proof of concept that uses only one request to the CSS but it seems a bit hacky to me and should be tested and verified. it also should be improved with some fallback if javascript is not available.

    CSS (external file test.css)

    div { border: 3px solid red;}
    

    HTML/jQuery

    <!doctype html >
    <html>
        <head>
           <!-- provide a fallback if js not available -->
           <noscript>
              <link rel="stylesheet" href="test.css" />
           </noscript>
        </head>
        <body>
    
            <div></div>
    
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
            <script>
            $(document).ready(function() {
    
                $.when($.get("test.css"))
                .done(function(response) {
                    $('<style />').text(response).appendTo($('head'));
                    $('div').html(response);
                });
            })
            </script>
        </body>
    </html>
    

    You should see the CSS code inside the div with a red border all around :)
    Enjoy.

    0 讨论(0)
  • 2020-11-30 05:28

    The closest you can get to obtaining the stylesheet without using ajax is to indeed iterate over all CSS rules and concatenate them into a string. This yields the original file with all comments and excess whitespace removed. Which makes sense, as the browser only needs to keep the parsed style sheet in memory, not the original file. It is only 3 lines of code:

    function css_text(x) { return x.cssText; }
    var file = document.getElementById('css');
    var content = Array.prototype.map.call(file.sheet.cssRules, css_text).join('\n');
    
    0 讨论(0)
  • 2020-11-30 05:33

    I think your best bet would be to load it with ajax with something like:

    $.get("/path/to/file.css", function(cssContent){
        alert("My CSS = " + cssContent);
    });
    
    0 讨论(0)
提交回复
热议问题