css3 - 关于CSS中@import的疑问
巴扎黑
巴扎黑 2017-04-17 11:48:35
0
4
549

对于@import,都不推荐使用

<style>
@import xxx
</style>

因为即便在头部书写,也会在页面结构被渲染后才加载css,造成页面的可能无样式的尴尬。

因此如果用sass的话,多个scss文件,通过一个main.scss @import之后编译成css再在html中引入就不会出现这样的问题。

那我想问的是,如果不使用sass,如果有多个css文件,在main.css中这样写:

@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,800,700);
@import url("normalize.css");
@import url("grid.css");
@import url("modal.css");

然后在index.html中引入:

<link rel=stylesheet href="css/main.css">

可以在浏览器中看到:main.css是优先于其他三个样式加载的,并没有以我们期望的方式按@import顺序加载,但整个页面显示却不会有任何的问题,请问是为什么?用链接唯一css文件,并且采用@import在css文件中引入其他模块css这种方式可取吗?

巴扎黑
巴扎黑

reply all(4)
迷茫

Not advisable. @import The incoming styles are loaded after the page content is loaded. If the network speed is slow, the page may flicker, so it is not recommended. Compared with this method, if you want to load many independent CSS files , it is recommended to load directly with link[rel=stylesheet].

If there is not a lot of CSS content, it is better to merge it into one file (on demand) to reduce requests.

小葫芦

Do you think browsers are stupid? There must be optimization, the previous IE6 may be what you think

巴扎黑

First of all, thank you for the invitation, but I am not an expert. My understanding is that it’s like external link CSS and in-line CSS. Which level do you think takes priority? It’s just a personal understanding. As for whether it is correct or not, please Baidu

黄舟

The first question is, main.css takes precedence over other styles that are @import. This is normal and should be. It is equivalent to main.css being the entrance, and other styles are introduced by it. of. The questioner thinks this is a problem because he thinks that CSS has the same order of execution as JS, which affects the priority relationship. But in fact, the browser will only apply the style to the DOM after all the CSS is loaded. In the tree, the priority relationship at this time is based on the writing method and introduction order of CSS code.

Second question, this method is available. The writing method of @import itself only has the problem of low loading speed in the old version of IE (8-), and modern browsers have been well optimized, so there is no need to worry about it anymore. However, the questioner still needs to pay attention to that each @import will generate a new http request. From the perspective of performance optimization, it is still like the Sass mentioned by the questioner, appropriately reduce the number of http requests and directly change the code Consolidating them into a small number of files will help the website load faster.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template