开发者

Correct way of loading multiple CSS in a page

As per Yahoo, we have to limit number of request to the server's to improve the website's performance. Agreeing to it, I would to combine my CSS files, but i am not sure which one of below method is appropriate or corrent one to go with.

Method 1

File: css1.css

.
.
.
.
.css开发者_运维知识库1style { }
.
.

File: css2.css

.
.
.
.
.css2style { }
.
.

Then File: parent.css

@import "css1.css";
@import "css2.css";

Method 2

Fle: parent.css

.css1style { }
.css2style { }

When we have a very large collection of style sheets, then the method 2 might create manageablity problem.

  • Which one is the corrent way?
  • If I go with Method 1, will I still be following the yahoo's rule, or not?
  • Is there a better way to do What I am attempting?


I would compress them into one file in order to reduce the http requests. Look at the HTML5Boilerplate's Build Script. It allows you to code in separate files and deploy in one minified file. This is always best practice.


The best way to do this is with some sort of build process which combines all our source css into one file (similar to your method 2) but retains the original CSS for development and debugging in multiple files. There are many tool which help with this and depending on your platform and any framewroks you are using different ones have different strengths. You might also like to take a look at sass if you're comfortable with ruby as well, it's great for organising CSS code. If you're using php I would heartily recommend minify, which does JavaScript as well.

Most of the tools will also compress our CSS for you too removing unnecessary white space while keeping your source stylesheets nice and clean.


There are some problems using @import

  1. Different browsers treat import differently (Was a problem in older browsers which may not be used now)
  2. I guess IE6 and IE7 do not support @media. In link tag you can specify media as screen, print, etc. But IE6 and IE7 do not support @media in CSS. So specifying media types would not be possible in IE6 and IE7 when using @import.
  3. Each import would result in a new HTTP request

Method 1 does follow Yahoo rules.

You may split your CSS into multiple files in Development environment and when deploying to production you can club them together.


Using method 1 would result in requests for the css1.css and css2.css files so you would make 3 requests as opposed to 2 if you requested the files seperately. Combining the files into a single file such as method 2 would conform to the Yahoo rules.


best way is to combine all the files, compress them with YUI compressor. you can find detailed help at this link

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜