LoginSignup
0
0

More than 1 year has passed since last update.

jquery と cssの読み込み順序について (importantも含む)

Posted at

cssの読み込みをする場合、読み込み順序がバッテングしてどれが反映されているかわからなくなることが合ったため整理してみた。

読み込み → style.css, preindex.js, index.jsの3つ
preindex.jsは上に配置、index.js下に配置
cssは上で別ファイルを読み込み、html上で定義しているものもある。

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="preindex.js"></script>
  <link rel="stylesheet" href="style.css">
  <style type="text/css">
    .test{
      background-color: gold !important;
    }
  </style>
</head>
<body>
  <div>
    <div class="test" style="width:300px;height:300px;"></div>
  </div>

  <style type="text/css">
    .test{
      background-color: black;
    }
  </style>
<script src="index.js"></script>
</body>
style.css
.test{
  background-color: yellowgreen;
}
preindex.js
let test = $(".test")
test.css(
  "cssText","background-color:red !important;",
);

//index.jsも同様

それぞれのファイルに背景の指定を行い、何が反映されるか検証。
jqueryを使ってcssをいじったらうまくいかなかったため、cssTextというプロパティを追加しました。
これは、完全にcssを上書きしてしまうもので全て書き換えてしまう。
つまり、widthを設定していたとしてもこの書き方をすれば、widthは当たっていなかったことになり背景だけが当たっていることとなる。
(プラス+ ではなく、削除してからプラスするイメージ)

結論

上から読まれ下の方が優先度としては高い という当たり前の結果に。
たとえjsが挟まれてたとしても、headでjsを読むのかbodyの下で読むのかによって優先度は変化する

より下に書かれているcssが反映され、!importantも例外ではなく
<style type="text/css">
.test{
background-color: gold !important;
}
</style>
にimportant
index.jsにimportantをつけたとしても、後に読み込まれるjsの方が優先されるみたいですね。
jsにdeferをつけたら、黒色(html上の最後のやつ)が優先されて、後に読み込んでも優先はされないみたいですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0