2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

<script async> で DOMContentLoaded が発火しないことがある

Posted at

async属性をつけた <script async> は非同期で読み込まれるため、
ドキュメントの読み込みが完了した時点で script が読み込まれていないことがある

その場合、読み込みの状況次第では DOMContentLoaded が発火しない

old.js
function main() {
  // 読み込み後に動かしたいコード
}

document.addEventListener("DOMContentLoaded", main, false);

改善策として、ドキュメントの読み込み状態をチェックする
document.readyState を見れば、状況が分かる

NEW.js
function main() {
  // 読み込み後に動かしたいコード
}

if (document.readyState !== "loading") {
  main();
} else {
  document.addEventListener("DOMContentLoaded", main, false);
}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?