Skip to content

Instantly share code, notes, and snippets.

@retorillo
Last active November 17, 2015 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retorillo/83b37b09adf7b73d93f6 to your computer and use it in GitHub Desktop.
Save retorillo/83b37b09adf7b73d93f6 to your computer and use it in GitHub Desktop.
jQueryの$()は何をしているのか、DOMContentLoadedとloadの違い

jQueryの$()は何をしているのか、DOMContentLoadedとloadの違い

jQueryばかりに頼っていると忘れがちなので覚書です。

$()は何をしているのか

$(function(){ ... })

上記のように、jQueryを使えば、$() を使いスクリプトの実行イベントを挿入できますが、 これをjQueryを使わずに記述する場合、 documentDOMContentLoadedにイベントを挿入し、 次のようにします。

document.addEventListener('DOMContentLoaded', function { ... });

もしくは、DOMConentLoadedに対応していないブラウザは windowloadイベントに挿入し、 次のようにします。

window.addEventListener('load', function() { ... })

ちなみに、jQuery 2.1.4 の実際のコードはこのようになっています。 まずDOMContentLoadedのイベントで処理しようとし、 それで処理できなかった場合はloadのイベントへフォールバックして処理しているようです。

DOMContentLoadedとloadの違い

DOMContentLoadedイベントはドキュメントのロードと(DOMオブジェクトへの)パースが完了したときにfireされるイベントですが、従来からあるloadイベントはページ全体(スタイルシートや画像なども含めて)のロードが完了したときにfireされるイベントで、2つは同義ではありません。

一般的にはDOMContentLoadedのほうがより最適なタイミングでスクリプトの実行が可能です。

DOMContentLoadedについてはMDNで以下のように記載されています。

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event - load - should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment