你真的知道为什么不推荐使用@import?

Use of @import

<style type=”text/css”>@import url(Path To stylesheet.css)</style>

Use of Link

<link rel=”stylesheet” type=”text/csshref=“Path To stylesheet.css” />

以下引自overflow

In theory, the only difference between them is that @import is the CSS mechanism(机制) to include a style sheet and the HTML mechanism. However, browsers handle them differently, giving a clear advantage(更明显的优势) in terms of performance(在性能方面).

Steve Souders wrote an extensive blog post comparing the impact of both and @import (and all sorts of combinations of them) called "don’t use @import". That title pretty much speaks for itself.

Yahoo! also mentions it as one of their performance best practices (co-authored by Steve Souders): Choose over @import

Also, using the tag allows you to define "preferred" and alternate stylesheets. You can't do that with @import.

以下引自Steve Souders的博客,Steve Souders是High Performance Web Sites的作者

use LINK instead of @import if you want stylesheets to download in parallel resulting in a faster page.(如果你想并行的下载样式进而得到一个更快的页面,则使用link而不是@import

区别:

  1. 在老版本的浏览器(低于ie5)不支持@import()兼容性

  2. link属于html,而@import则属于css

  3. @import可以在css中再次引入其他样式表,比如可以创建一个主样式表,在主样式表中再引入其他的样式表


以下总结自steves souders的博客

**原文:https://www.stevesouders.com/blog/2009/04/09/dont-use-import/**

**中文:https://www.qianduan.net/high-performance-web-site-do-not-use-import/**

**不推荐使用@import:**

**1. @import混合js文件时,在IE中引发资源文件的下载顺序被打乱,即 使排列在@import后面的js文件先于@import下载并且打乱甚至破坏@import自身的并行下载**

2. link混合@import会破坏并行下载,这是一个很严重的问题,这会导致原本并行下载的样式变成一个一个的同步下载

3. 而仅仅使用LINK 可确保样式在所有浏览器里面都能被并行下载,并且按照顺序被下载

**所以,不推荐使用@import而应该使用link**


扩展:@import用法注意

虽然不怎么使用@import但是对于@import的一些注意事项还是要知道

**import规则一定要先于除了@charset的其他任何CSS规则**

@import.css

#bgc{
    background-color: red;
    font-size: 30px;
}

<style>
    #bgc{background-color: green}
    @import "@import.css";
</style>

如果style是这样写,那么@import的样式将不会生效因为此时的@import.css没有正确的引入

改成这样则会生效

<style>
    @import "@import.css";
    #bgc{background-color: green}
</style>

这就是上面说到的**import规则一定要先于除了@charset的其他任何CSS规则**

同时这样写也是正确的

<style>
    #bgc{background-color: green}
</style>
<style>
    @import "@import.css";
</style>

猜你喜欢

转载自blog.csdn.net/qq_41813695/article/details/80489601