简体   繁体   中英

How can i read CSS rule from local file with JavaScript

what i want to do is to read what's inside a css file ( local file ) but

  • i cant use GET because i don't use a server and i don't want to
  • i don't want to allow chrome --allow-file-access-from-files
  • and i have an error that can't get the fille with protocol file://

my goal is to save an html file but before that to get the css from link stylesheet and add it to the html file between

css=' <style>\n'
    //+ get the css
    + '</style>\n';

The solution to your problem is:

<style>
@import url("style.css");
</style>

Classic way to link stylesheets.

JQuery way:

<!doctype html >
<html>
    <head>
       <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>

Use must have all paths as relative ones instead of absolute. And your structure should be like this:

root
 | - index.html
 | - css
 | -- styles.css
 | -- images
 | --- background.png
 | --- button.jpg
 | - js
 | -- main.js

Then you use relative paths in index.html:

<html>
    <link href="/css/styles.css"></style>
    <script src="/js/main.css">

CORS rules applies strictly in browser when on file:// protocol: all resources that are being requested must be on same level as current file or below (deeper in dir tree).

So if you have file in root/pages/index.html it can't request ../css/styles.css because of CORS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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