开发者

Is it possible to pull in all styles from external style sheets and put them on the same page?

Is it possible with javascript or jQuery to pull in all CSS rules that are listed in ext开发者_JS百科ernal files, then do $('link').remove(), then put all the CSS rules in style blocks on the same page?

To clarify: I want to move all external CSS rules into inline style blocks in the page with JavaScript, yes.

If so, how might I go about accomplishing this?


I've left out the details about appending the rules as "inline" rules. That should be fairly trivial. Also, you'll see below I have DISABLED the style sheets rather than actually removing them. the important thing I want to hilight is that this solution allows for stylesheets that import other stylesheets.

TEST.HTML

<html>
    <body>
        <link rel="stylesheet" type="text/css" media="screen,projection" href="screen.css">
        <link rel="stylesheet" type="text/css" media="screen,projection" href="screen2.css">
    </body>
    <script>
            function processSheet(sheet){
                if (sheet.cssRules){
                    for (var i=0; i< sheet.cssRules.length; i++){
                            if (sheet.cssRules[i].type == 3){
                                processSheet(sheet.cssRules[i].styleSheet);
                            }
                            else{
                                alert(sheet.cssRules[i].cssText);
                            }
                    }                               
                }
            }

            for (var i=0; i< document.styleSheets.length; i++){
                processSheet(document.styleSheets[i]);
            }

            for (var i=0; i< document.styleSheets.length; i++){
                processSheet(document.styleSheets[i].disabled=true);
            }   

    </script>

    <div>Hi</div>
</html>

screen.css

@import url("reset.css");
table {
    background-color:green;
}


Well you could do something like:

var $stylesheets = $("head link[rel=stylesheet]"),
    $style = $('<style>').appendTo('head');

$stylesheets.each(function() {
    var href = $(this).attr("href");
    $.get(href, function(data) {
        $style.append(data);
    });
});

$stylesheets.remove();

Keep in mind that this will screw up relative paths to images/fonts in loaded stylesheets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜