[jQuery]エラー:Uncaught ReferenceError: $ is not defined

Advertisements
Webデザイン

突然ですが、このようなエラーを吐き出したことはありますか?

main.js:2 Uncaught ReferenceError: $ is not defined

私は、あります。

原因は、シンプルにjs読み込み位置を間違えていたというものです。以下stackoverflowより。

The most common reason behind the error “Uncaught ReferenceError: $ is not defined” is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you’re executing the jQuery code only after jQuery library file has finished loading.

このエラーは最も散見されるエラーで、jQueryの実行コードをライブラリよりも先に読み込んでしまっている場合に起こるよ、読み込み順序適切か確認しようね、というわけです(意訳)

Uncaught ReferenceError: $ is not defined?
How come this code throws an Uncaught ReferenceError: $ is not defined when it was OK before? $(document).ready(function() { $('#tabs > ul').tabs({ fx...

ですのでこれを

<script src="js/main.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

こう

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>

めでたしめでたし

タイトルとURLをコピーしました