你真的知道為什么不推薦使用@import?


#Difference between @import and link in CSS

Use of @import

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

Use of Link

<link rel=”stylesheet” type=”text/css” href=“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>



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM