当前位置:网站首页>Relationship between link and @import
Relationship between link and @import
2022-07-29 05:40:00 【Try your best】
link And @import The difference between
We all know , External introduction CSS Yes 2 Ways of planting ,link Labels and @import.
What is the essential difference between them , Any suggestions for use , In the study of external introduction CSS This part of the content is , It's often mentioned .
Now , Many scholars have a learning attitude of knowing what it is and not wanting to know why , natural , Just for conclusion .
therefore , This article follows css hack The principle of progressive identification ,
Conclusion → difference → controversy → details → Ancestral graves → feeling , Gradually deepen the theoretical level ,
Strive for every level Readers of , can get To what you want , There is no need to continue reading .
Conclusion
As far as the conclusion is concerned , Strongly recommended link label , Use with caution @import The way .
This avoids thinking about @import Grammar rules and precautions , Avoid resource file download order confusion and http Ask for too much trouble .
difference
1. The difference in subordination
@import yes CSS Grammar rules provided , Only import style sheets ;link yes HTML Label provided , Not only can I load CSS file , You can also define RSS、rel Connection properties, etc .
2. Loading order difference
When loading the page ,link Label introduced CSS Is loaded at the same time ;@import Introduced CSS Will be loaded after the page is loaded .
3. Compatibility difference
@import yes CSS2.1 There is only grammar , So only in IE5+ To recognize ;link Label as HTML Elements , There is no compatibility issue .
4.DOM Controllable difference
Can pass JS operation DOM , Insert link Label to change the style ; because DOM The method is document based , Can't use @import The way to insert the style .
5. Weight difference ( This is controversial , This is explained in detail below )
link The introduced style weight is greater than @import The style introduced .
controversy
I don't know when to start , When you search the Internet link and @import Difference time , There is a quiet sentence in the stereotyped answer “link The introduced style weight is greater than @import The style introduced ”.
But there is no answer , With any explanation or example of this sentence .
What do you mean by this sentence , How to understand ?
Carry forward the spirit of exploration , We might as well continue to consult the information . It turned out , There are still many articles and posts , Question this sentence , Then I wrote it myself demo To verify , Results of validation , It really can't coincide with this sentence .
and , The author did not find it clear 、 correct 、 Explain this conclusion with reasonable and reasonable reasons , Still wrong article .
So this conclusion , Where did you come from at first , There may be no way to verify .
Another way of thinking , Don't argue about its right or wrong , Unsuccessful exploration , Let's start with the core keyword of this conclusion “ The weight ” set out , To study it .
Speaking of “ The weight ”, It is necessary to explain again :CSS Weight in , Refers to the priority of the selector .
CSS The weight of the selector is high , That is, the priority of the selector is high .
CSS The priority feature of the , The same HTML When the element is styled , Different selectors have different priorities , Low priority styles will be cascaded by higher priority styles .
CSS The weight priority order is simply expressed as : !important > Inline style > ID > class 、 pseudo-classes 、 attribute > Tag name > Inherit > wildcard
In order to understand the calculation method of weight , Let's do the numerical hypothesis analysis as follows :
Selectors The weight
wildcard 0
label 1
class / pseudo-classes / attribute 10
ID 100
Inline style 1000
important 1/0( infinity )
Give another example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css"> #myid {
/* id The selector weight is 100 */ background-color: pink; } #divid .myspan input {
/* The weight of 100 + 10 + 1 = 111 */ background-color: yellow; } input[type="button"] {
/* The weight of 10 */ color: white !important; /* !important The weight is infinite */ } input.myclass {
/* This is the label specific selector , The weight of 1 + 10 = 11 */ color: black; } </style>
</head>
<body>
<div id="divid">
<span class="myspan">
<input type="button" id="myid" class="myclass" name="myname" value=" Am I " style="background-color: blue; color: green;">
<!-- style The weight of the style is 1000 -->
</span>
</div>
</body>
</html>
Weight value of each style , In the example , Mark in the form of notes .
According to the weight value , Final , The style of this button must be , Blue background , White words , The results are as follows :
There is !important when , Don't make him think , It must be the style with the largest weight .
Now that we understand ,CSS What is the weight of , So back to the subject ,“link The introduced style weight is greater than @import The style introduced ”,
Don't CSS Does the introduction method of have weight ? In fact, we don't have to worry about whether it has weight , We just need to combine theory with practice to analyze , In all cases , What the result is .
As follows 3 individual css file :
/* green.css */
div {
background-color: green;
border: 3px solid red;
}
/* yellow.css */
div {
background-color: yellow;
border: 3px solid black;
}
/* blue.css */
@import url("green.css");
div{
background-color: blue;
}
example 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- example 1. link Tags introduced yellow.css, Inline style introduces green.css -->
<link rel="stylesheet" href="yellow.css">
<style type="text/css"> @import url("green.css"); </style>
</head>
<body>
<div style="width: 50px; height: 50px;"></div>
<!-- The box is , Green background , Red border , namely green.css take effect -->
</body>
</html>
example 1 The results are as follows :
example 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- example 2. Inline style introduces green.css,link Tags introduced yellow.css -->
<style type="text/css"> @import url("green.css"); </style>
<link rel="stylesheet" href="yellow.css">
</head>
<body>
<div style="width: 50px; height: 50px;"></div>
<!-- The box has a yellow background , Black border , namely yellow.css take effect -->
</body>
</html>
example 2 The results are as follows :
Comparative examples 1 And examples 2 These two opposite results are known ,link and @import It does not produce the effect of similar weight , It simply reflects CSS The layering of the structure , The style written later , Overwrite the previous style .
example 3:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- example 3. Inline style introduces green.css, Set pink background in inline style -->
<style type="text/css"> @import url("green.css"); div {
background-color: pink; } </style>
</head>
<body>
<div style="width: 50px; height: 50px;"></div>
<!-- The box has a pink background , Red border , namely green.css In force , But the background color is cascaded pink by inline styles -->
</body>
</html>
example 3 The results are as follows :
example 4:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- example 4. link Tags introduced blue.css,blue.css Introduction in green.css -->
<link rel="stylesheet" href="blue.css">
</head>
<body>
<div style="width: 50px; height: 50px;"></div>
<!-- The box has a blue background , Red border , namely green.css In force , But the background color is blue.css The layers are blue -->
</body>
</html>
example 4 The results are as follows :
Analyze examples 3 And examples 4 As a result, we can see :
For example 3, We see the red border , Prove the use of... In inline styles @import Introduced green.css Has to take effect , But its background style is overlapped by the pink background in the inline style , This phenomenon shows that ,@import Not just as we see , At the top of the inline style , The style it was introduced , On the structure , It's also true that it's placed before the inline style , So inline styles can stack it up .
Empathy , example 4 in , stay link Label introduced blue.css In the file , The top also exists @import Introduced green.css, The red border still proves ,green.css Has to take effect , But the background pattern is blue.css Its own blue background is layered ,@import The style introduced is blue.css Is also placed in front of its own style .
Only this and nothing more , I made a bold guess ,“link The introduced style weight is greater than @import The style introduced ”, The giver of this conclusion , I want to tell you :
stay link Label introduced CSS In file , Use @import Pay attention to , If the same style already exists ,@import The style introduced will be used by the CSS The style of the file itself cascades out , Show link The weight of the style introduced by the label is greater than @import The intuitive effect of the introduced style .
For my hypothetical conclusion , It seems to make sense , After all, this is the result of practice .
Those who have verified this conclusion , They are all in the same HTML On the page , Use one before the other link And inline style @import To compare , I'm giving examples 1 And examples 2 This is also the case in , It can't be reversed “link The introduced style weight is greater than @import The style introduced ” This conclusion , therefore , I think beyond my capacity , In fact, this conclusion initially just lost a known condition .
Then let's re sort out this conclusion : stay link Label introduced CSS Use... In the document @import when , The same style will be used by the CSS The style of the file itself cascades .
Ps. First of all, thank you for your reading . The author belongs to the learning stage , A little knowledge , Although the conclusion of this paper has been verified by the author , But the author's brain is short circuited 、 It's possible that the wording is wrong , It's all true love that is destined to read here , I hope you will 、 Daniel 、 Great immortal 、 The risk 、 The great gods do not hesitate to teach , Correct in time , To avoid inducing new people to go astray , Thank you again !
details
Since I have said so much , By the way, about @import Other details when using .
stay 《CSS Authoritative guide 》 wrote :
@import Be sure to write in addition to @charset Anything else except CSS Before the rules , If placed in another location, it will be ignored by the browser , and , stay @import Then if there are other styles , be @import The semicolon after that must be written , Can't be omitted .
Only this and nothing more , It seems that everything is clear , But then suddenly a doubt came out :
When discussing differences , Not when loading a page ,link Label introduced CSS Precede @import Introduced CSS Load it , that link How can the styles introduced by tags make @import The introduced styles are stacked up ?
Answer that question , First of all, let's clarify some concepts about browsers :
Browser execution can be simply divided into loading 、 analysis 、 Rendering , These three steps .
load : On request URL Domain name resolution , Send request to server , Receive response file ( Such as HTML、JS、CSS、 Pictures, etc ).
analysis : For the resources loaded (HTML、JS、CSS etc. ) Parsing , Build the corresponding internal data structure ( such as HTML Of DOM Trees ,JS Object's property sheet ,CSS The rules of style, etc ).
Rendering : Build the render tree , Calculate the position of each element 、 Pattern calculation, etc , Then complete the page layout and drawing process according to the rendering tree ( It can be understood as “ draw ” Page elements ).
These processes are not completely isolated , There will be intersections , such as HTML After loading, it will be parsed , Then pull out HTML Specified in the CSS、JS etc. .`
Now? , We should have understood the concept of loading and rendering , Understand that they are two different processes , Then continue to ask the questions raised above :
link Precede @import load , Is it before @import Apply colours to a drawing? ?
actually , Rendering actions are usually performed multiple times , The last rendering , The page must be drawn according to the integrated rendering tree of all styles loaded before , Page elements that have been rendered , Will also be re rendered .
Then we can put @import This import CSS The way of documentation is understood as a replacement ,CSS The parsing engine is working on a CSS When the file is parsed , Such as at the top of the file @import, Will be replaced with the @import Imported CSS All the styles in the document .
the path winds along mountain ridges , One good thing came out of , Finally, I found out why @import The style introduced , It's going to be stacked . It's then loaded , It will be placed at the top of the stylesheet after loading , The final rendering will naturally be layered by the following style with the same name .
So far, ,“link The introduced style weight is greater than @import The style introduced ” This conclusion , I finally got round for it . I hope the author of this conclusion , The original intention is as I guessed , Otherwise, if I am distracted and deviate , I can't imagine how much secret is hidden behind this .
Ancestral graves
Some careful and professional readers may have found , I use my own ideas and words , Roughly explained about CSS Knowledge of loading and rendering , Some inexperienced front-end fans may be confused , It cannot be used as a basis for systematic learning . It doesn't matter , Come out to mix , Ancestral graves are always planed , Want to thoroughly study relevant content , Scholars who further understand the underlying principles , I have already prepared a generous gift for you ~
of link and @import Comparison in performance analysis , Foreign masters have been writing for many years :
If you like your mother tongue, please poke me :https://www.stevesouders.com/blog/2009/04/09/dont-use-import/
Read English please poke me :https://www.qianduan.net/high-performance-web-site-do-not-use-import/
A masterpiece about the internal working principle of the browser , It was also from waiguoren bull a few years ago :
1 In Mandarin :https://kb.cnblogs.com/page/129756/
2 for English:http://taligarsiel.com/Projects/howbrowserswork1.htm
You who yearn for knowledge , Click on the portal above , I believe you will have a rich harvest .
feeling
I like reading other people's technical articles about exploration , You can not only learn technical knowledge , It can also learn the spirit of others' exploration and the logic of thinking . Maybe there have been many predecessors like me , The controversial conclusion of this paper , Have doubts , Think it over , Got his own opinion , It's just not written , Or not published .
What about the others , Is it just a simple copy or memory conclusion .
Actually I think , In our field , Don't ask for a better understanding , It's impossible to follow others . A sentence with information , When entering the brain , You have to think for yourself , Don't let our brains act as transponders , Worst of all , It has to be a parser .
I declare that : This content is reprinted. If you need to visit this big brother, please send me a link https://www.cnblogs.com/KilerMino/p/6115803.html
边栏推荐
- ·来一篇编程之路的自我介绍吧·
- [C language series] - three methods to simulate the implementation of strlen library functions
- Longest string without duplicate characters
- [electronic circuit] how to select ADC chip
- Provincial and urban three-level linkage (simple and perfect)
- 167. Sum of two numbers II - enter an ordered array
- Common shortcut keys for Ad
- Preemptive appointment | Alibaba cloud shadowless cloud application online conference appointment opens
- 微信小程序视频上传组件直接上传至阿里云OSS
- 数据库操作 Day 6
猜你喜欢
[C language series] - storage of deep anatomical data in memory (I) opening of summer vacation
Day 5
虚拟增强与现实第二篇 (我是一只火鸟)
全局components组件注册
Clickhouse learning (XI) clickhouseapi operation
Clickhouse learning (VII) table query optimization
ClickHouse学习(四)SQL操作
Playwright实战案例之爬取js加密数据
Day 5
Alibaba cloud Zhang Xintao: heterogeneous computing provides surging power for the digital economy
随机推荐
Flask 报错 RuntimeError: The session is unavailable because no secret key was set.
移动端-flex项目属性
重绘与回流的关系
[electronic circuit] how to select ADC chip
全局components组件注册
ClickHouse学习(一)ClickHouse?
Day 2
Together with digital people, digital space and XR platform, Alibaba cloud and its partners jointly build a "new vision"
uniapp组件之倒计时(如阅读协议倒计时、完成学习倒计时)
365 day challenge leetcode1000 question - day 036 binary tree pruning + subarray and sorted interval sum + delete the shortest subarray to order the remaining arrays
Common characteristic engineering operations
[sword finger offer] - explain the library function ATOI and simulate the realization of ATOI function
[C language series] - storage of deep anatomical data in memory (II) - floating point type
AR虚拟增强与现实
Selenium实战案例之爬取js加密数据
Alibaba cloud Zhang Xintao: heterogeneous computing provides surging power for the digital economy
Basic use of redis
Alibaba cloud and Dingjie software released the cloud digital factory solution to realize the localized deployment of cloud MES system
uniapp组件之选择选项(如套餐选择)
ClickHouse学习(七)表查询优化